diff --git a/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb b/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb index 2599e28..f4ec06e 100644 --- a/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb +++ b/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb @@ -9,9 +9,31 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\zfit\\util\\execution.py:57: UserWarning: Not running on Linux. Determining available cpus for thread can failand be overestimated. Workaround (only if too many cpus are used):`zfit.run.set_n_cpu(your_cpu_number)`\n", + " warnings.warn(\"Not running on Linux. Determining available cpus for thread can fail\"\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "WARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], "source": [ "import os\n", "\n", @@ -42,7 +64,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ @@ -68,7 +90,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ @@ -256,7 +278,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "metadata": {}, "outputs": [], "source": [ @@ -311,7 +333,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "metadata": {}, "outputs": [], "source": [ @@ -521,9 +543,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "WARNING:tensorflow:From C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\tensorflow\\python\\ops\\resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Colocations handled automatically by placer.\n" + ] + } + ], "source": [ "# formfactors\n", "\n", @@ -632,7 +664,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": {}, "outputs": [], "source": [ @@ -662,7 +694,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "metadata": {}, "outputs": [], "source": [ @@ -679,7 +711,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, "metadata": {}, "outputs": [], "source": [ @@ -717,7 +749,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "metadata": {}, "outputs": [], "source": [ @@ -761,7 +793,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "metadata": {}, "outputs": [], "source": [ @@ -777,7 +809,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, "metadata": {}, "outputs": [], "source": [ @@ -837,9 +869,32 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\ipykernel_launcher.py:14: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n", + " \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+17YcXAAAgAElEQVR4nOy9eXxV1bn//157nzFzyACBAAETDRDCKHAFFGetrdqWVqy21lq99ertvfW2Vzv39mq/1VptrVp/Dm3t1YrVDg5FW2friKjMY4AAgUDm6SRn3Ov3x97n5CQ5UyDJCWG9Xy9ePWfttddaJz3uz3me9aznEVJKFAqFQqEYDWjpXoBCoVAoFGGUKCkUCoVi1KBESaFQKBSjBiVKCoVCoRg1KFFSKBQKxajBlu4FjDYKCwtlWVlZupehUIx6tjVtIUvamVx0cp/2xraDNITamOKeSHZGfppWZ7KtaQvZOCgtrKClrYH6UCMTnYXkZ41P67rGIh9++GGTlLLoWMdRotSPsrIy1q1bl+5lKBSjngW/rWJFoISfX/dSn/aH//IDftnxF34+4zuct+jyNK3OZMFvqzjbKOWOa17kiWd/zU9a7+d707/IZcv/O63rGosIIfYNxTjKfadQKI6KkAANMaBd18zfuoYRHOklJUQX5rqCoVCaV6JIhBIlhUJxVBiAJgY+QsKiFAj5R3hFA5EChCWcQtMBCI0ysVT0RYmSQqEYNFJKpBAxLSXNEqVQKL0PfyklBiCEuUZdt9ZlKEtpNKP2lFIgEAhQV1eH1+tN91IUxyEul4vS0lLsdnu6lzJkhKT5YBcxftfaNPNzpl+UzP8NW0qaMNdlSCVKoxklSilQV1dHdnY2ZWVlkV9dCkUqSClpbm6mrq6OadOmpXs5Q4YhDSC2+07TzYd/0Eiv+05iuRgJW0qm+y6o3HejGuW+SwGv10tBQYESJMWgEUJQUFAw5qzssKWkxbSUwm6ydFtKpouR/paSct+NapQopYgSJMXRMha/O2FLSQh9wLXRIkohw/Tfhd134QCMkHLfjWqUKCkUikETCgWAONF3ugOAoNUnXUT2vfoFOqg9pdGNEqUxxOuvv84nP/lJAHw+H+eccw5z587lySefHND3P//zP3nzzTcBM5DjlltuoaKigqqqKhYtWsQLL7wAwE9+8pPIPW1tbdx///1Dslafz8dll11GeXk5ixcvpra2Nma/F198kVNOOYXy8nJ++tOfRtpXrVrFrl27hmQtisFjWOHegoGWkq6PjoACQ/a1lMLuu6By341qlCiNUT7++GMCgQDr16/nsssu63OtpaWF9957j9NPPx2A73//+9TX17N582Y2b97Mc889R2dnJzB8ovTII4+Qn59PTU0N3/jGN7j55psH9AmFQtxwww288MILbN26lSeeeIKtW7cCcP3113PHHXcMyVoUgydkJLCULDdZugMKDMt9F9736hVLI21rUiQnJVESQlwghNghhKgRQtwS47pTCPGkdf19IURZ1LVvW+07hBDnJxtTCDHNGmOXNaYj0RxCiAIhxGtCiC4hxL1x1v+sEGJzan+S0UdtbS2VlZVcddVVVFdXs3LlSrq7uwHTkqisrGTZsmX8+c9/BqChoYErr7yS9evXM3fuXHbv3t1nvKeffpoLLrgAgO7ubh566CF+9atf4XQ6ARg/fjyf//znueWWW+jp6WHu3LlcccUV3HLLLezevZu5c+fyrW9965g+0zPPPMNVV10FwMqVK3nllVfoXwV57dq1lJeXM336dBwOB6tWreKZZ54BYPny5bz88ssEgyqSKh0Eg5alFGNPyW4zv0fpzugQktb81pZeOPou3etSJCZpSLgwv3X3AecCdcAHQohnpZRbo7pdA7RKKcuFEKuA24HLhBAzgVXALGAi8LIQIpy9Md6YtwN3SylXCyEesMb+dbw5AC/wfaDK+td//Z8Bugb1V0nA/zy3ha2HOoZqOABmTszhh5+albDPjh07eOSRR1i6dClf+cpXuP/++7nxxhu59tprefXVVykvL49YRMXFxTz88MPceeedPP/88wPGevvtt1m5ciUANTU1TJkyhZycnAH9fvrTn3Lvvfeyfv16wBTHzZs3R973Z/ny5RELK5o777yTc845p0/bwYMHmTx5MgA2m43c3Fyam5spLCyM2QegtLSU999/HwBN0ygvL2fDhg0sWLAg/h9OMSyERUmLFeigjw5LKWSEgzH6uu9UoMPoJhVLaRFQI6XcI6X0A6uBS/r1uQR41Hr9NHC2ML8JlwCrpZQ+KeVeoMYaL+aY1j1nWWNgjXlpojmklB4p5VuY4tQHIUQWcBNwawqfc1QzefJkli5dCsCVV17JW2+9xfbt25k2bRoVFRUIIbjyyitTGqu+vp6iomNO5juAf/7zn6xfv37Av/6CBAywimBglFqyPsXFxRw6dGgIVq4YLOEUQrHdd+HQ63S778Jh61agg80MwAgp992oJpXDs5OAA1Hv64DF8fpIKYNCiHagwGp/r9+9k6zXscYsANqkDNvdffrHm6Mpwdr/F/g50J3oAwohrgOuA5gyZUqirkktmuGi/wM7/P5owo3dbnfk3Ex5eTn79++ns7OT7OzsY1rjYCyl0tJSDhw4QGlpKcFgkPb2dsaNGxezT5i6ujomTpwYee/1enG73ce0ZsXREbSyNcQMCbfcd+lO59MrPpalpGnoUqpzSqOcVCylWE+9/j9h4/UZqvZU19G7ICHmAuVSyr/E6xMZRMoHpZQLpZQLh8OCGAr279/Pu+++C8ATTzzBsmXLqKysZO/evZE9oyeeeCKlsWbMmEFNTQ0AGRkZXHPNNXz961/H7zd//dbX1/PYY48BYLfbCQTMTe3s7OyYohNmMJbSxRdfzKOPmobv008/zVlnnTVAYE899VR27drF3r178fv9rF69mosvvjhyfefOncyalZ4fCSc6id13o8NNJq1s4GFrTmg6GspSGu2kIkp1wOSo96VAf59JpI8QwgbkAi0J7o3X3gTkWWP0nyveHPH4F2CBEKIWeAs4WQjxesJPOoqZMWMGjz76KNXV1bS0tHD99dfjcrl48MEHueiii1i2bBlTp05NaayLLrqI119/PfL+1ltvpaioiJkzZ1JVVcWll14ace9dd911VFdXc8UVV1BQUMDSpUupqqo65kCHa665hubmZsrLy7nrrrsi4d6HDh3iE5/4BGDuNd17772cf/75zJgxg89//vMRETpy5Ahut5uSkpJjWofi6AgEw9F3sQIdTDeZIdO9p2RZc+Es4UI3LSWUKI1qpJQJ/2G6+PYA0wAHsAGY1a/PDcAD1utVwB+t17Os/k7r/j2AnmhM4ClglfX6AeDfEs0RtYYvA/fG+QxlwOZkn1VKyYIFC2R/tm7dOqBtJNm7d6+cNWvWkI65dOlS2draOqRjjiR33XWXfPjhh9O9jJRJ93doqPloxyuy6ndV8heP3zjg2raajbLqd1Xytj9cnYaV9VLbcEBW/a5K/uTRVVJKKddt3i4X/Wam/M7qy9K6rrEKsE6m8IxN9i/pnpI0929uBP5uCcpvpJRbhBA/thbxLPAI8H9CiBpM62WVde8WIcQfga1AELhBStOmjzWmNeXNwGohxK3Ax9bYxJvDGqsWyAEcQohLgfNk3+hART9+/vOfs3//fvLy8tK9lKMiLy+PL37xi+lexglLIJzRQRv4CLHZRsfh2fCeViT6TrehS5SlNMpJKUu4lHINsKZf2w+iXnuBz8W59zbgtlTGtNr3YEbn9W9PNEdZkvXXEiNc/HihrKyMzZuH9pjV4sX9Y1WOL66++up0L+GEJpxmSBcDHyGO8DmlNO/dGOGQcKL3lKTaUxrlqIwOCoVi0IQtJaHHsJTs4dDrNIeE98t9JzQNnfRbcIrEKFFSKBSDJhQMW0oxAh30cKBDei0SGbGUet13mkz/uhSJUaKkUCgGTTDBnlJv9F2695T6FiLULPedEqXRjao8q1AoBk348Gw4e0M0us1uhV6nOUt4ZP6+7ju1pzS6UZbSGGIslq4oKytj9uzZzJ07l4ULF0bav/nNb/Lqq68OyVoUgydopRnStRilK2xmlFu6H/7h6DtN9HPfqei7UY0SpTHKWChdEea1115j/fr1rFu3LtL27//+733qKylGlvDBVD2G+07TdHRk2t134XRCkT2lyLriJoJRjAKUKB0HnKilKxIxdepUmpubOXz48DGtQ3F0hDOA6zGi73TNLP0n02yRRELCI3tKmrKUjgPUntJgeeEWOLxpaMecMBsuTPyr/0QsXQFmOO95552HEIJ//dd/5brrrotcmz9/Pm+//Taf/exn4/7dFMNDxFISMfaUhECTEErzw1+GQ8Kt396aMH+Fq0CH0Y0SpeOE/qUr7rnnHs4555xI6Ypw+4MPPph0rOEsXZEqsayiWBnP3377bSZOnEhDQwPnnnsulZWVEbejKl2RPiKHZ2NYSppmykC6LZKI+y5sKVliqURpdKNEabAksWiGixOxdAUQKVVRXFzMpz/9adauXRsRJVW6In2ELaVYIeHAqIi+C/UTJT0ilmpPaTSj9pSOE07E0hUejycyn8fj4R//+AdVVb3Zonbu3NnnvWLkCO8p2WKEhAOjwlKS/URJiL7rOuw5zLX/uJamnkQl2RQjjRKl44QTsXTFkSNHWLZsGXPmzGHRokVcdNFFkQCNQCBATU1NnzBxxcgRdo3pttiipEvSHuUWkv2i78J7Xda6ntzxJO/Vv8dzu59L2xoVA1Huu+METdN44IEHBrRfcMEFbN++fUD7ihUrWLFiRcyxli9fzre//W3a2trIy8vD4XBwxx13cMcddwzoe/vtt3P77bdH3v/hD384+g8Rhcvl4qmnnhrQPnHiRNasMfP0Tp8+nQ0bNsS8//nnn2flypXYbOornA4ie0px3HcCkXZLibAoab3uO53eAIywtSeVO29UoSylE5Rw6YrjlWAwyH/913+lexknLGErJFxltj/6KAgoMCKHZ80DvkKY6wqLks0S1LA4KUYH6mfmcYAqXTGQz30uZhUTxQgRDnSwx3Pfkf6Q8FC/w7O6EH0yTShRGp0oS0mhUAyaiChprpjXbaPinFK/hKzCdN8FLXddOMN5wAikZX2K2ChRUigUgyZsXdjt8SwlQXCUnFMiSpRscuC6lKU0ulCipFAoBk24gJ9Nd8a8rsn0Bzr0FvkLpxnCyjRhWkphMVKW0uhCiZJCoRg0QeuB77DHFiUdEXn4pwsZqacUHRIuBkTfeYPe9CxQERMlSmOIoy1dsWLFCk455RSqq6uprKzkxhtvpK2tbVjX+te//pWtW7fGvf7AAw/w+9//PrK+6Azhw0Uq5TS8Xi+LFi1izpw5zJo1ix/+8IeRa6tWrWLXrl3Dvs7RQHhPyWGLI0ox3GQjTSQhK+bekSYEuhQDLCVvSInSaCIlURJCXCCE2CGEqBFC3BLjulMI8aR1/X0hRFnUtW9b7TuEEOcnG1MIMc0aY5c1piPRHEKIAiHEa0KILiHEvVHjZAgh/iaE2C6E2CKEOKHqHAymdAXA448/zsaNG9m4cSNOp5NLLrlkWNeXSJSCwSBf+9rX+NKXvjSsa+hPKuU0nE4nr776Khs2bGD9+vW8+OKLvPfeewBcf/31Mc96jUXCIeHhKrP90dHSbylZa9S0XvedQIsEOoQ/gy/oS88CFTFJKkpCCB24D7gQmAlcLoSY2a/bNUCrlLIcuBu43bp3JrAKmAVcANwvhNCTjHk7cLeUsgJotcaOOwfgBb4PfDPG8u+UUlYC84ClQogLk33e0chwlq7oT/gg7f79+2MeXO3q6uLqq69m9uzZVFdX86c//QkwUxzNnj2bqqqqPg/zrKwsvvvd7zJnzhyWLFnCkSNHeOedd3j22Wf51re+FVnfihUr+M53vsMZZ5zBL3/5S370ox9x5513RsZ57LHHOO2006iqqmLt2rUAvPHGG8ydO5e5c+cyb968hCmQUiGVchpCCLKysgAzq0QgEIikR1q+fDkvv/wyweDY3zgPyiSWEoKQSK8oReo5Wf//2KzSFWGxDO8lKUtpdJHKOaVFQI2Ucg+AEGI1cAkQ/TP3EuBH1uungXuF+V/qJcBqKaUP2CuEqLHGI9aYQohtwFnAF6w+j1rj/jreHFJKD/CWEKI8etFSym7gNeu1XwjxEVCawudNyO1rb2d7y8AMCsdC5bhKbl4Uv8gdDF/piljous6cOXPYvn07c+bM6XPtf//3f8nNzWXTJrN8R2trK4cOHeLmm2/mww8/JD8/n/POO4+//vWvXHrppXg8HpYsWcJtt93Gf//3f/PQQw/xve99j4svvphPfvKTfdbR1tbGG2+8AcCPfvSjPvN6PB7eeecd3nzzTb7yla+wefNm7rzzTu677z6WLl1KV1cXLtfA8OThKKcRCoVYsGABNTU13HDDDZEzX5qmUV5ezoYNG1iwYEHcv+9YwDBCCCnjWkqa1AiRXnE2IntK5mNO14S1rr7uO79VRVcxOkjFfTcJOBD1vs5qi9lHShkE2oGCBPfGay8A2qwx+s8Vb46kCCHygE8Br8S5fp0QYp0QYl1jY2MqQ444/UtXvPXWW2zfvj1SukIIwZVXXpnSWKmUrohXcO/ll1/mhhtuiLzPz8/ngw8+YMWKFRQVFWGz2bjiiisi+1UOhyOyz7VgwYK4Zc+BAW7GaC6//HIATj/9dDo6Omhra2Pp0qXcdNNN3HPPPbS1tcVMOTSYJLGpltPQdZ3169dTV1fH2rVr+xxsPlHKaQRlEBugxcnooAkt7ZaSpG85dLDcd0LtKY1mUrGUYtVG6P9ti9cnXnssMUzUP9V1DEAIYQOeAO4JW2YDBpHyQeBBgIULFyYcM5lFM1wMV+mKWIRCITZt2sSMGTO47777eOihhwBYs2YNUsoBcyaqGGu32yP9dV1P6NrKzMyMey3W57/lllu46KKLWLNmDUuWLOHll1+msrKyT7/hKKcRJi8vjxUrVvDiiy9GspWfKOU0DGlgkxI93jklqaW5cEX0OSU90mYGYJioPaXRSSqWUh0wOep9KdD/p2CkjyUCuUBLgnvjtTcBedYY/eeKN0cyHgR2SSl/kULfUctwla7oTyAQ4Nvf/jaTJ0+murqaG264IWJdTJw4kfPOO497743Ek9Da2srixYt54403aGpqIhQK8cQTT3DGGWckXEOyMhj9CUcQvvXWW+Tm5pKbm8vu3buZPXs2N998MwsXLoyZmHaoy2k0NjZGIhN7enoGCOHOnTuZNWtWyp/reCUkg9gk6PECHYQesUjSRfjHkhb1mNPQCAnzWthS8oWUKI0mUhGlD4AKKyrOgRm48Gy/Ps8CV1mvVwKvSvMb8SywyoqcmwZUAGvjjWnd85o1BtaYzySZIy5CiFsxxes/U/ico5rhLF0BcMUVV1BdXU1VVRUej4dnnnkm5r3f+973aG1tpaqqijlz5vDaa69RUlLC//t//48zzzyTOXPmMH/+/KTRe6tWreJnP/sZ8+bNGxCIEYv8/HxOO+00vva1r/HII48A8Itf/CKyDrfbzYUXHlscSyrlNOrr6znzzDOprq7m1FNP5dxzz424J48cOYLb7aakpOSY1nE8YMgQNiS6rse8rqGleUcpuhBh72MuXBo9KIMErb0kdU5plCGlTPoP+ASwE9gNfNdq+zFwsfXaBTwF1GCKzvSoe79r3bcDuDDRmFb7dGuMGmtMZwpz1GJaTV2YFtVMTCtLAtuA9da/ryb7rAsWLJD92bp164C2kWTv3r1y1qxZQzrm0qVLZWtr65COeaJz1113yYcffjjmtXR/h4aaG35zrjzj4RnSHwzFvP4fvz5DLvrN0H5nB8vql38lq35XJZ/6x92Rtu/etVhW/a5Kdge65Y1PXSSrflcllz+2OI2rHDsA62QKepLsX0pZwqWUa4A1/dp+EPXaC8RM2yylvA24LZUxrfY99EboRbcnmqMsztIHv+FyghAuXZGXl5fupYwZ8vLy+OIXv5juZYwIpqVkZt6OhS70tFtKvdF3MSwlI0jA1wGA11DRd6MJldHhOGC4SldUV1cP6ZgnOldfffUJU3QwJENoEjQttihp6ATT/JPQkGH3Xa+LMZzdIWgECVli5TOCCYN1hooPDn/AiidXsKc9ZryVwkKJUoqMxJdWMTYZi98dA4ktwceyCR1DiEhNo3QQSTMUFX2nRVlKYUvOQI5IpvDndj9Hs7eZf9b9c9jnOp5RopQCLpeL5ubmMflwUQwvUkqam5tjHuw9ngkRSvjwCB9YDcr0OfHC9ZR0LTr6zlxXwAhE0g3ByJxVave1A3Coa+yfYzsWTgxfwzFSWlpKXV0do/VgrWJ043K5KC095mQio4qQNNBlfP9cRJRCAZxxylsMN6EYe0palPsuWpR8IR/ZZA/reuo99X3+VxEbJUopYLfbmTZtWrqXoVCMGkIYCS0lW1iUgj5wZI3MovoRrvmka9GPuag9pWhLaQTCwlu85rHKhu6GYZ/reEa57xQKxaAxklhKuiVKgWD3SC1pAOE9pWhR0qJKoAdkb2mNkThA2x0w/xZtvuEtC3O8o0RJEZedtZu4Z/XX070MxSjEtJQSiJJmph8KBHtGakkDCKcRsunR0Xe9e11BGcJpCddw7ylJKekKdAFKlJKhREkRl+/84woe8r3Gjr3r070UxSgjhEwoSpowRcnnT1+2hHDpij6WUvSekjTItIKXhjtTeE+wB4kky56FJ+AhEFIl2OOhREkRlxY9nLBSpWFR9MUgsfvObllKXn8a3XexRCnsVgwFCGGQGbaUhvk7HraSJmWZRQ+UtRQfJUoKhWLQJLOUwkLgDaTvB00osqcUlSUcy60YChCUkizDtJSGe0/JE/AASpRSQYmSQqEYNIZIJkpm9nC/L317SmFLyab1ltfQLbeiP9htuu9GaE8pIkrZSpSSoURJoVAMmhASPcHjw6abouQdBYEOWh9LybTgfIFu/FF7SsNdU0m571JHiZIiOVGhswoFWO47mVyU/Gl034UzOtij8hHqmnmQ1xf0EkRGLKWRct+VZpmHqJUoxUeJkkKhGDQh0bd4Xn8cuplWKa17SuFAB9ErSjZhiWWwh1CUKA13oENYlCZmTQR6Uw4pBqJESZEcob4mir4EkegJ9pTstrAoeUZqSQMwLEvJpkdH34VFyYsBIxbo0OU33XcF7gKculOJUgLU00aRHOW+U/QjKMBG7KqzAE5bJgC+QPr2lGTYUooSJZsW3uvqxhDgkhIh5bAHOnRbmS2y7FnkOnOV+y4BSpQUCsWgCQjQE4iSwxEWpfSdUwqFLaWoQAebtafUbVlwNilxyhEIdPB3YdfsOHQHec48JUoJUKKkSI5y3yn6ERBmddl4uCxR8qbRUoq476JCwtFcCCnxWO40GxLXCFhKXYEuMu3m3yTPmafcdwlQTxtFcpT7ThGFlJIgid13bmcOAL40hoQbWIdno9x30ubEKWXEUtIlOKUx7JaSJ+CJiFKuM1eJUgKUKCkUikERlEGkEH2i2vqT4TJrE/nTmKIqvKdkjxYlzYFDysgeT9hS8g1zNnNPwEOW3SzhofaUEpOSKAkhLhBC7BBC1Aghbolx3SmEeNK6/r4Qoizq2ret9h1CiPOTjSmEmGaNscsa05FoDiFEgRDiNSFElxDi3n7rWiCE2GTdc48QIn64kCI+yn2niCKcTDShpeSyLKURKAkRj4j7ztZbZNDQTUupx7LgbBKchsQ7zHtf0ZZSnjOPDl+HqmQdh6RPG2EWuL8PuBCYCVwuhJjZr9s1QKuUshy4G7jduncmsAqYBVwA3C+E0JOMeTtwt5SyAmi1xo47B+AFvg98M8byfw1cB1RY/y5I9nkVMVD/8SiiCBimKIVT9sTC5cpClxJ/WkXJSjNki1qn7sAhoTsiSmFLaXjdjP33lIIyGMnyoOhLKj+BFwE1Uso9Uko/sBq4pF+fS4BHrddPA2dbVsklwGoppU9KuReoscaLOaZ1z1nWGFhjXppoDimlR0r5FqY4RRBClAA5Usp3pfmT5PdRYykUiqMknKVB1+KLkt3pwiElfmN4S0IkQkbOKUWVY7eZ6/JYIiSlRpZhDLtAdAe6++wpgcrqEI9URGkScCDqfZ3VFrOPlDIItAMFCe6N114AtFlj9J8r3hyJ1l2XZN0ACCGuE0KsE0Ksa2xsTDCkQqEIV5MNZ0eIhcOZgVNKAmkUJUOGEFJii0ozJMKBDla0XQg7WYZBp79zWNcSbSnlOkxR6vB1DOucxyupiFKsfZj+/px4fYaqPdV1pLKmgY1SPiilXCilXFhUVJRgyBMTtRGniMZvWRWaFl+UnE47DklaLSUDAx0Q0Rkd7Kal1G25Ff2Gg2xD0jnMmSeiAx3yXHmAspTikYoo1QGTo96XAofi9RFC2IBcoCXBvfHam4A8a4z+c8WbI9G6S5OsW5ECEhUSrujF57MOniYQJYeuYZcQiDg9Rh4pQ2gSRFSRP93htETJFMsgDrINg65hjL4LGSF6gj3KfZciqYjSB0CFFRXnwAxceLZfn2eBq6zXK4FXrX2cZ4FVVuTcNMxgg7XxxrTuec0aA2vMZ5LMERMpZT3QKYRYYu1VfSlqLMWgULaSopceS5T06L2afjhtpigF0yhKhjTQkRB1yFezuUz3nWXB+aUpSl4jMGwlyj1B8+8VHegASpTikVSUrP2bG4G/A9uAP0optwghfiyEuNjq9ghQIISoAW4CbrHu3QL8EdgKvAjcIKUMxRvTGutm4CZrrAJr7LhzAAghaoG7gC8LIeqiIvmuBx7GDLDYDbwwmD+OwkQoUVJE0eMPW0rxRUkIkX5LCcN8wEXXU3K4cEtJyPLk+6WTbCtTeGdgePaVuq1w80zDgHfvI0czk9WqA7SxiX/6LQop5RpgTb+2H0S99gKfi3PvbcBtqYxpte/BjM7r355ojrI47euAqljXFArF0eG1LKVweYp42KUgYIVlpwMpLVGKOp6o211kGL3uaL90khUWJX8n41zjhnwd4QzhmXvehI//hC1nEtn2bCVKcVCnIhVJkQnjSRQnGj1+M5zabk8sSjapESB9omSELaUobHcgMjoAACAASURBVA4nGVFef590khMlSsNBxH3XbgUDH96osjokQImSIimGyn2niMJrue/sNnfCfjYpCKQxSMa0lPr+oLLbbLiidNJvuCM1lYZNlKy/V1a3JUJtB1RS1gQoUVIoFIMiXCPJ6chI2E+XGgGRRlHCQOtn5DttGs6oMu5ewx3ZU+rwD8+5obClZOtqNedp2EeuS1lK8VCipEiKodIMKaIIi1JSSwk9rZaSIQe67xw2DYfRu8fkkxmMM0zTqdXbOizrCO8p5XpNy8horyPXoUQpHkqUFHFRUqSIRbhGksuZlbCfU+r4RPq+RQZywAPOrmvYjd5WqbnJCpqHHpq9zcOyjnBG8hwrZ6DL10K+K3/YRPB4R4mSIjmG2lNS9OK3ag857Yndd3Z0vGk8TWBgoPfTRNNS6g0Rd2ouQtjJFQ6ae4ZHlCLRd4bBHmMCLtlDkTOf7mA3nmHOJHE8okRJEZfw80S57xTR+KwaSeGaSfGw4cCrpS9QJoSB3u+MnUPXsEWJksPmphsX+diGTZQ8AQ9OzY4d2C3N9JvFuun6bOxWuTb7o0RJERclRYpYhEuHZ1jpcuJhF2bIuDdNhf5CMralhOxNj+S0u+iQGeQb2rC579p8beRaIrRbTgSgyDoi2tDdMCxzHs8oUVIkRabxrIli9OEL+dCkJMOVmbCfXZgZH7qHuaprPELCwNZflHQNR7A3E4XTnkEXbsYZctgspXZfO7nWQeNDWgkAWT5zYQ09SpT6o0RJoVAMCr/hwyUldmeSPSXNtA56/OkpZheSckBtXIdNwxnsjRp0OJ10SjfjgqFhtZSyrRzTgbwyADJ7zH055b4biBIlRVKkoRx5il58hh+XlDhciTM6OHVTtLq7h+dhnwwz0KHfnpJNwy971+1wOOkkg/GBAD3BnmE50NruaydbmvJoLzwJAL2zjQxbhnLfxUCJkiIphipdoYjCbwRwGRKnM0nuO5sZMt6dptDnkJADAx1sGt3SxQOHG3j80GGcThdd0s1Eq5ruoa6hr27T7m8nMwQBqZM/fgqGFPg7myjOKFaiFAMlSgqFYlD4DT8OCQ574nzOLrsZndfRnajs2fARYqD7zq4LPLhY2uOl2ufH6TQtpSk+c9/rYNfBIV2DlNJ034WgEzdlxTm0kYnRpUQpHkqUFEmRKvedIoqADJiipCd+fDgdOQB0dKfHUjKQA913ukY3vRaeyxKlqT4z791Qi1J3sJugESQrEKRTZjCtMIsWmYPobqYks2RYLLPjHSVKCoViUPhlELsU2JKIUjhkvKMnPel0TEuprygJIQhovYEOdlcWndJNrmGQbc+irrPuqOYypBGpmxRNOJAhPxigkwwKsxy0iVxs3hYmZ0+moachbSHzoxUlSoqkJCjwqzgB8RPEbiRP1eB25QPQ5R2eRKfJiLWnBBCMytknHBn0aGZo+6SMYuq6Bi9KhjS4cs2VnP+n8znsOdznWtg9V+Tz0ykzyHXb6bLl4fK3UJpdCnDUQjhWUaKkSIrK6KCIxk8Im0z+6Mh0m6Lk8Q1PSYhkhJBoMpYo9YayC0cGPisgY1rGBHa37R70PFuatrCpaRNtvjYe2/pYn2tHuo8AUOzvoQs3mQ4bPfZ8MoOtTM6eDMCBzgODnnMso0RJoVAMigAGNtk/hGAgmRkFQG89oZHGEBI9xiMuZItKJOvIoNtmiufJzgLqPfWDrqv0UcNHAMwtmssLtS/0SasUtpRKfB68eiaaJgi4CsgyOpicaWZ3OBrrbCyjREmRHBXooIjCLwxsA+LaBuLKzCHTMPAE03R4FokmBq6z29Fb8lyzuQhaJdBP1k2xqmmrGdQ8e9v3Ms41js+f8nkauhvY1LQpcq3eU0+2PZu8oAe/JYaGuwANSV7IIMuepSylfihRUsRFOe0UsfAjsZE4HBzAmZFDjmHQmbY0Q8S0lHzOwshrm64RcpvvK6QdgJ0tOwc1z972vUzLncYZk8/Aptl4qfalyLXa9lqm5ZbhMjwErRB5PasIAOlpYnL2ZPZ17BvcBxvjpCRKQogLhBA7hBA1QohbYlx3CiGetK6/L4Qoi7r2bat9hxDi/GRjCiGmWWPsssZ0HMMc3xBCbBFCbBZCPCGESHzaTxETFRKuiMYnJDbsSftlZGSTHTLwhNIkSoAW4xHndxVEXjvtOlrGOEJoTPD1kOvMZXPz5kHNs6d9D9Nyp5HjyGHpxKW8UPsCIatw4J72PZRlTUbHIOQwRcmeUwxAZ0s9J+WdNGjLbKyTVJSEEDpwH3AhMBO4XAgxs1+3a4BWKWU5cDdwu3XvTGAVMAu4ALhfCKEnGfN24G4pZQXQao19NHNMAr4OLJRSVgG61U8xSKSymRQWhjTwC7CL5KLkdtrINAQeo2cEVjaQoJCIGO473Sq5cVAW4LRpZGc4aCMH0dPMvKJ5rG9Yn/IcXf4u2nxtkaCFT07/JA3dDaw7so7G7kYaexo5OcssVyGd5rktV/54ADwtR6jIr6Chu2FY0hsdr6RiKS0CaqSUe6SUfmA1cEm/PpcAj1qvnwbOFkIIq321lNInpdwL1FjjxRzTuucsawysMS89yjkAbIBbCGEDMgB1Uu0oUMF3ijA9wR6kENhxJu2b6dRxhTQ80j8CKxuIAegx9r4y7DorfD/n074f47Rp5LjsNMsc8DQxb/w8ajtqU84YXu+pB2CiFbRwxuQzyLRn8tTOp1h7eC0AC7KnAyCcphhm5U8AoKf9MBV5FQDsat119B90jJGKKE0Confi6qy2mH2klEGgHShIcG+89gKgzRqj/1yDmkNKeRC4E9gP1APtUsp/xPqAQojrhBDrhBDrGhtV1t7+KPedIky4UqpTS+4Jd9t1nIYND8GkfYeDoAAthii5HTq1soQG8nHadHLddhqMbGRXA/OL5wPwccPHKc0RFqWSLLMkhdvm5guVX+DvtX/nznV3Mj5jPDNc5h6S7jYPE+cVTMCQgkBHAxX5lii1KVEKk4ooxTol1/+3c7w+Q9U+6DmEEPmYVtQ0YCKQKYS4MkZfpJQPSikXSikXFhUVxeqiUCjoPXPkjMqKEA8hBHZpxyNGvh5XyAgREgKbGBiQ4XZElUO3a+S47TSQj+w4xKyCWWTZs3jr4FspzRM+LFuSWRJp+0rVV5hZMJMWbwv/Mf8/CHWbrjlbRh4ARTkZtJKF7GpkfMZ4sh3ZylKKIhVRqgMmR70vZaAbLNLHcpXlAi0J7o3X3gTkWWP0n2uwc5wD7JVSNkopA8CfgdNS+LyKfihLSRHGY7m1nFriWkphHNKJT0AgFBjOZQ3Ab5guw1iilBktSjaNXLedOlmI6KzHjmDZpGW8fuD1lMq4H+o6hE2zUejujejLcmTxh0/8gX+u+iefOulTdHeYfzN7lnkeKsdto4VcRHczQghmjJvB1uatSefa07aHI54jSfsd76QiSh8AFVZUnAMzWODZfn2eBa6yXq8EXpVmbppngVVW5Nw0oAJYG29M657XrDGwxnzmKOfYDywRQmRYe09nA9tS+7MoolFbSoowXVYZCpc9cdXZMA5M8Wr3j+xGvj9kilKsgIzcjKhy6DadHJeNg7IIIUPQcZAVk1fQ7G1mY+PGpPPUe+qZkDEBTfR9lOqaTo6VkNbX2WTOlW0KlxCCDi0Ph88Uq+qiana07EiYA6870M2qv61i1d/GfqxWUlGy9m9uBP6O+VD/o5RyixDix0KIi61ujwAFQoga4CbgFuveLcAfga3Ai8ANUspQvDGtsW4GbrLGKrDGPpo53scMiPgI2GR91geP4m+kUJEOCot2j/WAteem1N9h5ZXr8I9s/rvwAz6WKI2LFiW7RmG2kzppWTrtB1heuhyn7uT5Pc8nnafeUx/ZT4pHsNMUn4zcXmuqy15Alt/M9lBdWE1QBtnWEv83c01bDT3BHpp6msZ8ZvHkJ+AAKeUaYE2/th9EvfYCn4tz723AbamMabXvoTd6Lrr9aOb4IfDDWPcoUkflvlOE6fCYD1iXIz+l/k49XL6iCXKnD9u6+tPlMwMy7JpjwLX8zF6hynTYKM52UietveS2/eSULePsKWezZs8avrnwm7hs8YM66j31LJow4HHVh5CnmQ7pJiez1+XpcY0nv+NtMAyqi6oB2NCwgXnF8+LOE2Z7y3YmZk1MOOfxjMrooFAoUqbdKtjndo9L0tMk0272a+4Y2fxuHq+Z2sgRQ5TGZfa26ZqgMMtJvSxAIqBtPwCfqfgMnYFOXtr30oD7wwSNIA3dDX2CHGIhu1tok1nkZfSKoT9zInaC0N1EgbuA0qxSNjRuiDtGdPbxve17E853vKNESZEUFeigCNPpNfeGMqI29hOR5TCzFzSPsMup2xIluz7wPFW0+w7AZddxuzNodZRA4w4ATp1wKtNzp/Obzb+JG/BQ76nHkAaTsvqfkOmL7m2hlWxy3b2ipOeZZSt8zaYIziuex0cNHyWcK9OeSaG7UImSQqH2lBRhPL4OdCnJyEhNlLIzTCuioXNoK7omw2O57xwxRKkwy2zLdvXuXhRlO6mzTYHG7QBoQuOrs79KTVsNbxx4I+Ycte21AJTlliVci83XSpvMItvVK0ruwqkAtB02x1gycQkt3hZ2tsbOu1ffVU9JZgnTc6ezt0OJkuIER6UZUoTp8neRYUjc2Xkp9bfnlJAfCnGk83DyzkNIt89y38UQJU0T/OHaxTz1tX+JtBVnO9nFZGjaBVb4+oXTLqQ0q5R7199L0Bh4ALi2oxaAqTlTE67F4W+nS89B13qPVOZOKAPA02iOsaRkCQDvHXov5hj1nnomZE5gSs4U9nfsTzjf8Y4SJUVSlCgpwniCHrKkgTs7tUAHPaeEglCIxp6mYV5ZX3rCohQnSOG0kwqpnJATeT8hx8Vm/0QwAtBsFvqzaTa+seAb7GzdyZ92/mnAGLXtteQ4csh3JvhbSEl2oJEOW0Gf5gkTJuGVdvwtZjKa4oxiTso9iXfr3405zGHPYUoySyjLKaPN1zamc+UpUVIoFCnTGfSQEzLIzsxK3hnIyB9PQdCgZaRDwv2WKKV4nmpKQQbvd5s56TjcWw/p3KnncuqEU/nV+l/R1E9YtzRvoXJcJUIIeOtu819/V3dPK3YZwOMs7tM8Ic9NvSxAtPcGgCyZuIQPj3yIL+Tr07c70E2rr5WSzBKmZE8BGNPlLpQoKZIi1Z6SwqLL8JIVEmS7k2cJByjMySA7JGgJjWz1WZ9V7dbpSE08pxZksMMoxbBnQt3aSLsQgu8u/i7eoJfvvf29yH8LPcEedrTsMMO56z6El39k/qt5pe/AHWaARyBjQp9mu65Rr08k09MrLssmLcMX8g1w4R3uNl2fEzInRFyFSpQUCoUC6MKP2xBkOVM64khRlhN3yEGr9I/ojxtvwLSUXCmLUiYhdNrGVcP+vqJwUt5J/NfC/+Ltg2/z8KaHAXjn0DsEZZBTJ5wKB963egr48Ld9B7ZEiZyBYeMt7skU+g5ErKvFExaTZc/ilf19he1wV29+vdLsUjShjWlRSu2bpTihUSHhijBdBHEbNmx6ar9n8zMduAMu/MJHs7e5T4644aTbct9lulLb+yorMN18+zJmM672YfB1gbNX0Fadsor1Deu55+N76An28O6hdyl0F5oHZz98EtzjYO4X4P0HwNMMmeYektF2AA3Q8yYPmDOQOx1Xtxc6D0NOCXbdzvLS5bx+4HWCRhCbZj6eD3lMYSvJKsGhOyjJLBnTwQ7KUlIkRbnvFGB+D7qEgdMYeCA1HnZdwx0y6wiNZHqcnqDpvst0pxYlmJ9hJ8dl42MxA6QB+97uc10Iwa3LbuWi6Rfx0KaH2NK8hW8t/JYpHI07oKgS5qwCIwhb/hy5z3t4G93SibugdMCc9uKTAeg6tD3SdvaUs2n1tfYpnXGo6xC60BmfYRYHLMspi0T+jUWUKCkUipTwBDyEBNhJXkspGpcwU/gc7By5rA49QQ9Ow8BpVZlNhhCCmRNz+FvHdLBnws6/D+hj1+z8dPlP+dPFf+K5Tz/HJ6Z/AqRENm7n3c4Crny+m1DRTNiwOnJP6MgOdssSinIGZlXPmzwDgOb9vRnCl08y8+79vbZ3/kOeQ4zPGB+xnKbkTGF/5/4x+2NRiZIiKRLlvlP0Zvq2k9o+TRi73dycP9gS+2DocNAT6iFTSuzO1KLvAKom5rL5cA/G9DNNUYrz0D85/+Tes0meJkRPKy815PFWTRPvZJ4DB9dBUw1IiaNpKztlKZPHDaw/VTq1nG7pxFffm4g1w57BWZPP4oW9L0Si8Oq76vvkupuaMxVPwEOzN7XquMcbSpQUcRmbv8MUR0ubtw0Au5aTpGdfZGYZ+aEQB1trhmNZMekJ9pBhGLgyUhelWZNy8AUNjpScCR11cOij5DdZGSB2yUksmJrPbQeqkEKDjauhuQanr4kPjEqmFgxcx+SCLHYyGWfTlj7tl1ZcSoe/g9cOvIaUktqOWqbkTIlcH+sReEqUFEkxDGUpKaDdShXktKUWPBBG5k1hUjDIgc6R25zvNnxkGhKXO3VRmj3J3H96x74EdGcfN1xcmsxcea0Z0/j62RVs92RxpPh0eP9BeOMODASbXQtiRivqmqDOdTKFXTv6WGWLJyxmQuYEnt75NA3dDbR4Wzgl/5TI9anZpiiN1WAHJUqKuISToqiMDgqAxnbzl3lWv4OgycgsnsZ0f4Aaz8ilGvJKH5nSICMztT0lgJOKMinKdvLG/gDM+CRsegqCvsQ3Ne6gR7jJKZ7K8vJCphVm8r+BL5gBD5v+yDvOpWQWT4t7u69gFpnSg2ytjbTpms4XKr/A+/Xv89CmhwCoKqyKXC/JKsGm2cZssIMSJUVclBQpojliWUq5mQPDmxNRXFhIqV+j2eih1apcO9z4pB+nIdB1PXlnCyEEp51UwDu7m5Fzr4CeVtj854T3yMYd1BgTKR+fjaYJrlwylb8dymLXJc8SuOiX3ND1VeZOiR8BmFG2AICmXR/0aV9VuYpidzFP7niSCZkT+oiSTbNRmlWqLCXFictYjfJRDI7DHfVkGAbZMQ6CJqI0302WzwyOqGkbmX2lLvxkhQb/eFtaXkhTl4+t7vlQNAPeuSdhlnyjYTs7jElUFJufb+WCUtx2nYe223k75xO0hxycOjV+7anJpyzAL3Xad/c9sOu2ubn/nPu5+KSLuX357QPKrY/lsHAlSgqFIiUaupsoCoVw5RYN6r7SfDdBnylku1p3DcfSBtAlgmQYg88NcHZlMbom+NumI7D0P6Bha8zwcAB6WtE9R6gxJnKSJUq5bjsrF5Typ48O8oNntpDrtrOsIv6B4ZMnFbJJnoTr0NoB104Zdwq3LbuN+ePnD7g2JWcKBzoPEDJCg/6Mox0lSorkqIwOCqDJ10phMIR73OAspVy3nWajjHGhEFuiDoUOFz3BHnxC4jZSy88XTUGWk6XlhTy38RCy6rOQX2bmtAsNLF1BgxnKvV1OpqK4d+/qvy84hdmTcqlv7+GHn5qJyx7fheiwaezLmsuErq3g7064ti1/+zUfv266EyvyK/CFfOzrHHsReEqUFElR7jsFQEuoi7wQ5OcVJO8chRCCtqyTmev18fHhD4dpdb2EQ9fdcnCHfMNcPGciB1p6eHdfB5z7Y2jcBh//38CODeah10OO6RRm9Wa5yHbZ+cu/ncbm/zmfz8wfmMlhAFNPw0YIz57YZSsA2ur3MuuDW5j3+tV093QzY5x58HZ78/a49xyvpCRKQogLhBA7hBA1QohbYlx3CiGetK6/L4Qoi7r2bat9hxDi/GRjCiGmWWPsssZ0HMMceUKIp4UQ24UQ24QQvVW9FApFykgpaZVeMoIO8jMHb4FQPIP5Xh8HvI00djcO/QKjaPWZwRROBmZRSIVPVpcwLtPBb96qhRkXw5TT4JUfQ+eRvh0Pb8IjMskpnmqWr4hCCIHTllqQRWn1mYSk4MjGV+L2ObCtd89p54evMz1vOnbNzvaWE1CUhBA6cB9wITATuFwIMbNft2uAVillOXA3cLt170xgFTALuAC4XwihJxnzduBuKWUF0GqNPeg5rHt+CbwopawE5gC9R6cVKaNCwhVtvja8QuIKusnPSD33XZjCSdOp8JqPmw+PDK+1FBa9TC31cPBoXHadKxZP4ZXtR6hp7IJP/QL8HnjuP/oGPex7h4/kKZSPP7p5wlSXT2Yj5ThrX43bx3tkd+R1x94PsWt2yvPK2dYy9h5pqVhKi4AaKeUeKaUfWA1c0q/PJcCj1uungbOF+dPhEmC1lNInpdwL1FjjxRzTuucsawysMS89mjmEEDnA6cAjAFJKv5SyLbU/i0KhiOZglxkO7g7lYk8xQ3g0FeNz8PSUkWvA63WvD/Hq+nKoy8yxl20b3HmqaL58WhmZDhu3v7gDik6Bs38AO1+Ad35ldmjdB007eTNQycnHKEouu05N3jImdW9DdtTH7tS6l07pppVc9CObAZhRMIPtLdvHnHs9lW/XJOBA1Ps6qy1mHyllEGgHChLcG6+9AGizxug/12DnmA40Ar8VQnwshHhYCBHzeLcQ4johxDohxLrGxuF1LRyPGCrQ4YSnzkqmmqEf3YP+5PFZfGycwpmeLt488AaBUGAol9eHQ617cBgSl3ti8s5xKMhycv2Kk3hp6xHe3d0MS/4NZl4KL/0A3vs1/PNOJIK/hZZwyoRjEyUAV9VFADR89FzM6+7OfRzWSzicUUGhx8whWDmukjZfG0e6j8S853glFVESMdr6S3O8PkPVfjRz2ID5wK+llPMADzBgPwxASvmglHKhlHJhUdHgwl1PBMbaLzHF4AknU810DO7gbJiywkw2iErO9vTQGejinUPvDOXy+lDXXktJKIiwSj0cLV9ZOo0p4zK45c8b6Q4a8OkHoOI8ePEW+Oj3bJt8GYcoPGZLCWDRomUclAV4Nj0f83qe7yBt7lK8+acw1ThAR7c3EuywpXlLzHuOV1IRpTog+ptYCvQvjBLpI4SwAblAS4J747U3AXnWGP3nOpo56qSU4bKQT2OKlEKhGCQHW3aRFwphz51+VPfbdY1AyQIWeKFIOFi9I4W8ckdJTUct0/wBtJxjEyW3Q+dnK6vZ19zNrX/bBnY3XL4arngaLnuMBzOuozjb2Sfy7mgZn+vm44ylTGp+F7wdfa7JUIDxoSP4sqfinDQblwhQu3MTleMqsQkbmxo3HfP8o4lUROkDoMKKinNgBhU826/Ps8BV1uuVwKvS/Hn9LLDKipybBlQAa+ONad3zmjUG1pjPHM0cUsrDwAEhRDiT4dlAb+ESRcooS0mxr72W0mAQreDoRAmgemoxb4eqWdnVzVsH32J32+7kNw2SnmAP+72NVPoD6LmDO08Vi8XTC/jX06fzh/f38+QH+0HToOJcZOUneW9vG4umjRsQeXe0BGZ8Bid+GtY+1ae9tX4vdhFCjJtOUfk8AFr2rMdlc1E5rpINjRuGZP7RQlJRsvZvbgT+jhm99kcp5RYhxI+FEBdb3R4BCoQQNcBNWG4yKeUW4I+YYvAicIOUMhRvTGusm4GbrLEKrLEHPYd1z78DjwshNgJzgZ8M9g90IqOkSBGmpucwJ/kDuIuPXpTmT83nxeACLm86TJbu5q4P7xrCFZpsa96GgaTCF8RRUDYkY37r/FNYXlHI9/66mVe2mfs36w+0cbjDy+kVQ+fuP+2MC6iV4+n+sK8V2XzAzETuGl9OYVk1IQTBw2aww5ziOWxp3kLQiHG49zglpTwcUso1wJp+bT+Ieu0FPhfn3tuA21IZ02rfgxmd17/9aOZYDyyMdY8idaQKdDihafO20WJ4Ge+3M7Ewfh63ZCwsy+ebxkLuEG6u1Yu5u+5N1uxZY1ZwHSLePvQ2moQJPdk48lIvW5EIm65x7+Xz+eJv3udf/+9DbjiznHd3N5PltHHB7AlDMgeYLry/5p7Dp9qfwGg/hJZrBmp46s39vHGTKxGODI7YJpHZZgpVdWE1j297nJ2tO5lZ0P+kzvGJyuigiEtv6QolSicy4SSqGb4cygqP7kAqQHG2i5MmjecVx1l8qWYt8wqq+J93/4ctTUOzUW9Igxf2vkB1ABpCJUzIObqMDrHIzbDz+FcXc+7M8fzylV2s29fCjy6eRY7rKA4SJyB70RXoGOx/9aFIm9FUQ490UFJqWqnt2RWU+PYSDBnMKZ4DwMbGjUO6jnSiREkRF+W+UwDUhJOoBkooynIe01hnVhbzs/YV6EaQnxkF5Lvyufala3mz7s1jXueavWs40HmAL7Q1sYkKct1DLBguO7++cgFvfGsFb99yFisXpJBCaJAsXbyEd6kmd/PvI/n2nB21HNRKcDlMx5ZRNJMpHGHf4UYmZk6k0F04pvaVlCgpkqICHU5sth75kLxQCK9rxjFv6p83czx7jBJ2ln6W8euf4Ddzv8mkrEnc8MoN3PT6TWxq3HRU37d3D73Lre/dyuzMUs7zdFObMXvIAhD6M7Ugk5Jc97CM7bLrHD7lS+SHmmj44E8AFHbX0OiaGumTM3UOmpDU7fwYIQTVhdVjSpQGn9tdoVCcUGxsWE+1z49v3LHvWVRNymXWxBx+2HkpqzPfYuKam3nsy8/zyO6/8OiWR3lp30tMzJzInKI5lOeXU5xRTL4zH7tmx6bZkEh6gj10B7rp8Hewr2EjH+/4C1scNspyyrirx0mnyKW18Pg9/bH0wi+wf/sd2F+/g0DlMsYbDWwqXBW5Pr5iPrwEnv0bgQuYUzyHVw+8SnNPMwXuwSXLHY0oUVKkgLKUTlQ6/B3s7jnChT4fwbKq5DekwKpTJ/P9Z7aw7dK7mPHSl3A+cTn/dvmTXDnzSl7Z9wpv1r3Jx40f80LtC0nHcqNTYYT4ZnuAy4pn4trwAPfJz1NWHL/a62inOC+TJ6b+G5fv/xFtD3+KPMB98orIdUfhdLw40JvMvHfzis0w8fWN6zl7lhvM1gAAIABJREFUytlpWPHQokRJkRRDue9OWMIHMyf2uHBMGZo9lJULJvPLV2r48cYsnvj8/8FTX4b/bzk5593Kp6tW8umKTwPgDXpp7Gmk3ddO0AgSMMzURBm2DNxoZG19lsLXf4ZmBCCjEN5/AO/JF/PLjRfx3aKsIVlrujjvc9fz2s+f58yudayTM5i36PTei5pOg2sa+V3mXt/MgpnYNTvrG5QoKRSKMc67h97BLiX+njLmluQMyZhuh84NZ57E/zy3lTX/Mp9PXPsK/OVr8OdrzYJ6Mz4Fpafiyi9jcsY4Jgs3SB90NUHLXjjwPtS8Aj0tUHE+fOZBcGRBwMPbe734N66jcgjy0aWTgmwXBV95krv/8RwLFq8gw9k3aKMnv5Lph16jqdNLYbaLWQWz+HgECiiOBEqUFCmgQsJPVN4+8AYLvF52aFV8Jn/oNve/uGQqf/7oIN/762bmfX0ZJde9Adufg48fhw9/B+8/EP/mrPFQfg7M/yKULYdwQIOey7p99dh1wZzJx6/7Lkz1lEKqv3p1zGu20nkU1j/D2pptFM6bx9ziuTy+7XF8IR9O/dgiJNONEiVFfIYneElxnHDYc5iazn1c2u1le9GCIY1ms+kad31+Dp++/x2u/u0HrL5uCXkzL4GZl0AoAI3boeMQdLeYoqPbIXsi5E+F7JJeIerHmzsbqS7NS1iCfCxQPPMM+ABat/8TLFH63ZbfsbV5a2SP6XhFhYQrkqJCwk9M/l77dwDmdVsRX0NMxfhs7r9iPnsaPXzm1+9Q09BlXtDtMGE2nHw+zL0c5qyCqs/C1H+BnIlxBammoZMthzq4sGrosiyMVrKnzqEbN1qdmW96btFcgDHhwlOipIiPpUVKlE5M/rbneWb5Q+zxzWbR9KMvmJeI008u4v+uWUSLx88n7vknd720k7Zu/1GN9atXa3DZNS6Z27/c2xhE06nPrmJy10b8QYMCdwFTc6YqUVKMcZT77oRlZ+tOtrVs51Od7bwh5zNvSv6wzbV4egH/+MbpnDtzPPe8sovTfvoq33hyPS9uPkyrJ7lASSn53dt7eWb9Ia5dPp2i7ON7TyVVjMmLOZkDbNlr1jidWzSXDQ0bjvsfkWpPSZGU4/1Lrhg8j219DBca53b5eGPKWbgdw7tHU5zt4r4vzOffz+rgt2/V8uKWw/zlY7MEe1lBBuXF2UwZl8HEPBdZThtuh443EKK+3ctr2xvYUNfO2ZXFfP3simFd52hifNWZaFvvpW7D68yruIp5xfN4Zvcz1HbUMi13WrqXd9QoUVIoFH1o6mni+T3Pc6nHy9rAApbNPmnE5q6ckMPtK6u59dNVfLivlY/2t7LhQBv7mrt5Z3cT3f7QgHtmluRw66VVXL5oCrp24pj3ORVL8WNHr30DuKr3EG3DeiVKirFJOBBcZQk/sXhgwwMYRpAvtzTx/dBV/HTmsVVwPRrsusaS6QUsmd6bNkdKSYc3SLc/iMcXwmXXGJfpIMNxgj7G7G7qsudwUscHeAMhynLLyHHksL5xfeQA8vGI2lNSJEW5704c9rTt4emdT/O5oB0RKiIw9YxhSz46WIQQ5LrtlOS6KS/OojQ/48QVpDAnnckpYj8fbdmOJjTmFs897oMdlCgpFAoAQkaIH77zQzI0B9cf3MM9/k+xasnx6wY6EZg0/0IADq9/ETDz4O1t30ubty2dyzomlCgp4qLcdycWv93yW9Y3ruc7XUECoph/us7i/Fkj77pTpI6zdB6dWg4ZdW/9/+3deXxU1d348c93ZrIRtkBYQiBsCUJYEiCAAiL7IpsLtlhR2tJqrd186k+rfbSPtvb10D5VW7W1FG2r1lLFQpFFQEEFBcK+JDEQNlkCISvZZzLz/f0xV4gxIZMYmMnkvF+vvHLvmXPPOffA3G/uveeeC1x+XmnfhX3+bNZXYoKSYRh8cuYTnt/7PFNb92HmuaP8vPwuvjuhP2GO4J4Zodmz2cjtdD3Jrr18llvKoOhBOGyOZn0JzwQlo04eayCTuaUU3A4XHOahDx8iPrI7T2ZsIzVkJAda3cBdo+L83TTDB5EDp9NVCjiwZyvhjnASOySyLyfIz5REZLqIZIpIloj8rJbPw0TkX9bnO0SkV7XPHrXSM0VkWn1likhvq4wjVpmhja3D+swuIntFZLXv3WLA5bcomYEOwSszP5NF6xcR4Qjj+exziK0N9xd/m1/MGRT088cFi05DZwLgSl8LQHLnZA7lHsLldvmzWY1Wb1ASETvwIjADSATuFJGar6BcBBSoajzwLLDY2jYRmA8MBKYDf7SCxJXKXAw8q6oJQIFVdoPrqNa2HwMZvnWHYbQcu8/vZtGGRYTZQ/lriYOu+Z/x3bIHGNo/npsHB//8ccFC2nTldKsB9C74mMoqN8mdk3F6nKTnp/u7aY3iy5nSSCBLVY+pqhNYBsytkWcu8HdreTkwSbxTCs8FlqlqpaoeB7Ks8mot09pmolUGVpm3NLIORKQ7MBNY6lt3GNV5Ls0zZM6Ugs2KIyv4zobvEBXajr+WRxD3WSr/Y/8hJ1sn89s7kpp0RnDj6nP2mcwQstibceQLD9E2R74EpVjgVLX101ZarXlUtQooAjpeYdu60jsChVYZNetqaB0AzwEPU88LgUTkXhHZJSK7Lly4cKWsLYoJRcGn1FXK4x8/zhOfPMGI6GRez6+g+/GP+V3ED1leOZI/LRhGh8hQfzfTaKBuI27BJkr27jVER0TTvXX3ZjvYwZegVNufTDWPV3Xlaar0BtchIrOAHFXdXcvnX8ysukRVU1Q1pVOnTvVlb3E8aoaEB4N9OfuYt2oeq46u4ru9ZvPHjFTaZh/kqYiHWVI8hqULUxjSvfm/HK8lCu8xjEJbFO1ObwK8zyvtzdnbLO8H+xKUTgM9qq13B87WlUdEHEA7IP8K29aVngu0t8qoWVdD6xgDzBGRE3gvD04Ukdd92F/DorUsGc1PUWURT257knvW3YOqh792m8mPPlyC2wP3yC9ZXjaMv35zBKP7Rvu7qUZj2WzkdL2JFNceTuYUktw5mfyKfE4Vn6p/2wDjS1DaCSRYo+JC8Q4qWFUjzypgobU8D9ik3hC9CphvjZzrDSQAqXWVaW2z2SoDq8z/NKYOVX1UVburai+r/E2qusDHfjG4PCTcaJ486mHFkRXMXjGbFUdWcHevm3k7v4JhW1/kaNQYbsj/BSdCE/j3/aMZHW8CUnPXPmkWbaWMjNT3Lt9XaoYP0dY7cZSqVonID4D1gB14RVXTROQpYJeqrgJeBl4TkSy8Zy/zrW3TRORNIB2oAh5QVTdAbWVaVT4CLBORXwF7rbJpTB1G0/A0w0sALZmqsvXMVp7b8xyHCw6T3HEQ/62Due7DpVSFtuG3bR7hxTNDmJscyy9vGUTb8BB/N9loAp2Tp+Na58BzeD19Z95Gm5A27M3Zy5y+c/zdtAbxaTZDVV0LrK2R9kS15Qrgjjq2fRp42pcyrfRjWKPnaqQ3uI5qn38AfFDX50btTChqfvZf2M9zu59j1/lddG8dy+KYKUzf8zZSeZFdUTO5L3smEtmJ388f0DLe0NqShLXhVJtkEoo+wVmlDOk8pFmOwGvhU+waV+KpZckITPty9vGXg3/ho9Mf0SG8A491ncC89M2EFG3jZLuR/KRsHvuzu7NwdC8enNLPnB0FKU2YSsKeX7PtwD6GdhrKC2deoKiyiHZh7fzdNJ+ZoGTUST9/VsWcMgUkVWV79nb+cvAv7Dy3k6iw9vwo+nru+nQrrTL+zrk2g3iSx1h3fiAzB3fjN5MTSOjSxt/NNq6i7qNuhT2/Jn/vaobO9M4gvv/CfsZ1H+fnlvnOBCWjXmqiUkDxqIcPTn3A0oNLOZh7kM7hHXk4KoXbM7fSqvQAJyOH8JT7W7x/IZFJ/buwZmo/BnZrPn8pG40X1qUf5x3daH/2IwZ2fAi72NmXs88EJSPImIEOAaHUVcrKrJW8kfEGnxV/RmxEZ56ISGBO5lbC3Hs51GokTzu/yy7XQOYmd2fd2N4MiGnr72Yb11hBt3EMPbmCc3nl9O/Qv9mNwDNByTAC3Oni0/zz03/y7yP/psRVQlLrnvyQTkxO3wW2cNbZJ/Bc2SRypRcLborj9zf0onPbcH832/CTjkkzafXZMjJTNzA0ZijLDy/H5XERYmse9xFNUDLqZYY5XHuqyp6cPbye/jqbTm3ChjAlogd35V4k6fgWCh2deM59J69XjKdnjx7cNzWOWUkx5vXgBp0GT8b5Tggc2Uhy0nxez3idzPxMBkUP8nfTfGL+Bxs+MGHpWil2FvPO0Xd46/BbZBVm0c7Rim9LR7528gAxVcfZ7Ujme855bNeRzBwWxz9GxZn7RcYXhbbidNthJBTtwN7O+6TM3py9JigZQcTcUrrq0nLTePPwm6w7vo7yqnIGhnbkFyUeZuZm4pR2vOGawT+rJtA+uh93To3jd0ndiAwzX1+jdpIwmfjdT7Ml6xzdIruxN2cvdyfe7e9m+cT8rzbqZUbfXR1lrjLWHl/LW4ffIj0vnQhbCDM0gjvOnmBQ5WdsZzA/dd7GgcgxzBrRi6XDYulnhnQbPogdMQd2P03+vjUkX5fMznM7UdVm8UoSE5QM4xpSVdLy0liZtZLVx1ZT6iol3hbJo4VlzC7Mo4yOvOmawU9lAomDkrlzWCzP943Gbgv8g4kROEK7XEeuoytR2R8xZMw3WXt8LTllOXSJ7OLvptXLBCWjXuZM6avLLc9lzbE1rMxaSVZhFmFiZ3KFh6/nnaN/pbDWPYL73DchvcZy6/A43h7Uldbm8pzRWCIUdLuJYSf/Q5H1EoX0vHQTlIwgYWJSo7g8Lj46/RErs1ay5fQW3OpmkIbyeF4+00tLSa/qzz/c3+Jkl0lMTornt0ndiG0f4e9mG0GiY/LNtP7sXzgzT2ATG2l5aUyIm+DvZtXLBCWjXuZMqWEOFxxmZdZK1hxdTX5lAdE4WFBUxK3FF3E4O/B21XS+HzWVkUOH8f0hMfTp1NrfTTaCUIeBk3GuchCa9QF9r+tLel66v5vkExOUjHqpefNsvXLKclh3fB1rjq0mI/9THAjjyiq47WIR/crCWee+nt9ETiT+hnHMTo7lwS5tmsVNZ6MZC2vN2bbJxBft4rr2s/kke2uzGOxggpJhNFKxs5j3Tr7HmmNrSD2XiqIMcLp5pPgiNxYr21wpvBU+npiUycxK7sG3urcL+AOCEVy09zgG7H+GNq5o8ivyOV92nq6RXf3drCsyQcmolcdd7T2JZu67S5xuJ1vObGHNsTV8eGozTk8VsVXKvcUXmVzi5EhlElvCxnMieTpTh/Tkaz2jsJmRc4afxCRPg/3P0PZsHgBpeWkmKBnNU2VVxaXllh6SPOph9/ndrDm6ho0n1nGxqowot3J7SQnTSsopKO/PtlbzWJ08m8lJfVlszoiMABEel0KZtKLXmUzs3eyk56UzKW6Sv5t1RSYoGbWqrCyvttbywpJHPRy4cID1x99lw7E15DgLifAoE8vKmFpcgbP0OvZHzmN78iwmJPfjv2PMPSIjANkdnI1KYXDePnq3HUxaXpq/W1QvE5SMWpU7yy4tt5TRd58Hog1WIDrvLCRElTFl5fywpBJbyXV82mY8R4bNYlJyAtM7m1FzRuBz9B1Pz/yP6CRdychLC/jBDiYoBbl5S1MY1jqJx+a/3KDtKipKr1KLAouqciD3ABuOrWX9sTWcdxZdCkT3l7qgpB+ftZ9C3vCbmZLclzkdW/m7yYbRIN2GTYOdTxGdX8E2Wz7nSs8R0zrG382qk09BSUSmA78H7MBSVf3fGp+HAa8Cw4E84OuqesL67FFgEeAGfqSq669Upoj0BpYBHYA9wN2q6mxoHSLSw8rfFe8010tU9fcN7aDmLjOkkszKVB5r4HYXy/IvLWuQDXRQVQ7mHmTDkZWsO/YuOe5iQlQZXV7BfSUubGUDKOw2g7AJMxmbGEf7VqH+brJhNFpo14EU2jqQkHsaOntndmjWQUlE7MCLwBTgNLBTRFapavUnsRYBBaoaLyLzgcXA10UkEZgPDAS6Ae+JSD9rm7rKXAw8q6rLROQlq+w/NaKOKuCnqrpHRNoAu0VkY412B7WKyrL6M9XhYklBE7bE/1xuFzvPpfL+p2+z+cxWLmg5DlXGlFdwT4mN8Kpk6DWDXlOmM7R3Fxx2m7+bbBhNQ4Tz0aOYkvMJz0kH0vLSmNQzcAc7+HKmNBLIUtVjACKyDJgLVD+4zwX+x1peDrwg3ouWc4FlqloJHBeRLKs8aitTRDKAicA3rDx/t8r9U0PrUNVtQDaAqhZbZcfWaHdQu1B4vtHbllYUVltrnmdKF50X2XJyExvT32JbQRpl4ibc4+GG8goSStsQFTKatgPmMjRlLD06Rvq7uYZx1YT3m0D3nHXEhCQG/GAHX4JSLHCq2vppYFRdeVS1SkSKgI5W+vYa28Zay7WV2REoVNWqWvI3pg4ARKQXMBTYUdsOisi9wL0AcXFxtWVplgqKshu9bUnFxUvLnmZ0+e5MyRk2H1nF+sxVHKw4jVugY5WbyWWVdC3vRnTUVGJG3cqIQf3N+4iMFiN22HTY+jAx5d5h4YE82MGXb2VtLa95lKorT13ptV0buVL+xtTh3UikNfA28BNVvVhLXlR1CbAEICUlpfkcgetRVJLb6G3LKmvtqoCjqqTnprEx/V+8f3ITJ6x/4j5OF7eXKtHu/nTpcSvXTZ7BgB6dzYOsRovk6NCTHEcM8ReL2GUvCujBDr4EpdNgzX3u1R04W0ee0yLiANoB+fVsW1t6LtBeRBzW2VL1/A2uQ0RC8Aakf6jqv33Y16BSVG2wQkOVBfDlO6fbSerpraw78A+25u0jX5zYVEmuqGR0WSSdQ0fRPXEeQ1PG0rmtmXXbMADyokcwPv9DlkW1C+jBDr4EpZ1AgjUq7gzeQQXfqJFnFbAQ2AbMAzapqorIKuANEXkG7yCEBCAV79nNl8q0ttlslbHMKvM/janDut/0MpChqs80tGOCQYkVlKQRl98Kyy80dXO+kqLKIj488g5r05azu/wYFaJEeDyMLHcSV9GF7lFT6DP6awxN7EeYw+7v5hpGwAnreyPDz7+DjaiAHuxQb1Cy7t/8AFiPd/j2K6qaJiJPAbtUdRXeg/9r1iCDfLxBBivfm3gHF1QBD6iqG6C2Mq0qHwGWicivgL1W2TS0DhEZC9wNHBSRfVYZj6nq2sZ1VfNTUlEEQGgjTnQuVhZUu8jqnzOlUxdPsf7A67x3fAMZ7lw8AtFVbiaWeejqTqBv3G0MnDabPjEdA/b6uGEEitjkyYR9rHTWNqTnB+54L5/u9FoH8rU10p6otlwB3FHHtk8DT/tSppV+jMsj9KqnN6gOVd1K7febWoyySm9QCmnEmVKp++KloHStnlPyqIdD5/awes/f2JqTyimbd6qjvk4Xs8vC6RGaQkLinQwfcSPtzLNDhtEgYdG9ybVF07usioy8jIAd7GCGHwWxUqf3vlBjzpQKPEW0dnsoucrP61S6K9matY41+95gV9lhCmxubKokVboYVRlN3/YTGXzjAgb164fdDFIwjMYTIadDCinlu9lWERGwr7EwQSmIFVbmgR1aacMP5hdsFXStspNl1yaf+66wvIC1e1/l/aw1HHBnU2GDVh4Pw8s8xHl6kxh3G8PH3E5sdFST1msYLZ2jz1hG7t8ERATsayxMUApixe4isHvnWGqIopJ8sh3KqMo2ZFHcJG05VZDF29v+zMfnPuaw7SIeETpVVTG2LJReYckMH3g3w1PGE2GeHTKMqyY2eTK2nY8jCBl5GQH5GgtzBAhi+VoCgLuBZzrv7ngNtwjxrQfySdX2Rt1TUlUOnNrOitS/kFq0n1MOJwDxVS5mVHbguqhxjBr9bQbEJwTkdW3DCEaRMf0poB0xrhDS8wJzsIMJSkFKPR7OOioBG1UNPOZvPr6CVnYPNwy4hVcPbvf58p1HPXyYtorV+15jT2UWuQ4PNlUGudyMqOxBUo+5jLtxAdHt2zV8hwzD+OpEyG4/jIEVGewJ0JkdTFAKUh/sWUGB3YZDtUFBaVfGJnY4chlT2YGO7eu/3qyq7MrazFupfyK1MpM8uxLqUZKcwhT3dVzffwGjr59JeGjIV9gbwzCaTK+xDD+aysaKEHLKcugS2cXfLfoCE5SCUG7hWZbs+TURIR6SnG05FOLblEGncrJ4/OMf08qm3D/xGWziHXmn+uW7UiXlRby88Zesz3mPUyFuHKokV9qYFT6cSSn3kzxoZMD9BWYYBsQmTcKZ7n37UHpeuglKxtVzLu8zXljzEJuq0igOs3G3/QbOu09RJfUPVlix5c/84fDzFNvhwU4LGZgwglPZRwCocjsv5SsuK+R3q37Eu+V7KLUJ8R43812DmDr8AVKSx5lAZBgBrl3cEGJcYYhCen46E+Im+LtJX2CCUhA4mZ3Ji+/+Pz7kKGU2G8Nc4czr831mj1/Ewy/PvOLlu407l7F03/+RHlpJjCpP9Pwv5kxcBEBkK++9H6fHG5TWbH+V36X9lgsOSKlwMLnbfG6b9hMiwsOv+j4ahtFEbDZyWyfTw3WctNzAG+xgglIzlnF8N0s2PcYW2xmcAiMrIrlj8I+YNmbBpTx2cVAlgsftxma/PCfcxwfX8uftT7E3tJT2dg93uBP53i1/oHP05UkaIyPaAlDlcfL39b/m2ew36KrKI+3v4hsLfobNvAjPMJolT9xoks6lszXnoL+b8iUmKDVDH+9fy2upi9kR4n049vrKttw5/BHGpcz9Ul67eP+JK1wVtLJHcuhYKr/f9BA7HPlE2pU5rj58b+Yf6BHT+0vbhoWG41Al25XN+rNv0Ncl/HbGcvr06H/V99EwjKunW/IUElf9kXdcBVwou0CnVp383aRLTFBqJopK8vjbu79kS/4HZIa5CXN4GOfswsIxv2DYwJvq3M5h8456K6u4yOK3vsM77oPY7DDV2Y3vTXuW+J4Dr1hviCo7w0po7VaeGLfEBCTDCAId+wynZ6X3ykl6Xjo3tar7GHKtmaAUwIpK8nj7gxfYcfY99ofkU2qzEWvzcLsOZMHEx4nvObjeMuw275QOD795OzvDihlZEcEDN/6OYQPH+dSGcpv3Et2Nnp4k9R/9lfbHMIwAYbMRETYI0ZMcyk3jph4mKBl1yMk7zfIPn2dn7oekhRRTbrPRxuEh2dmeCb2/xryJD2B3+P7P5rCFgAd2hhUzw9Wd//3u6i/cW/LVwvFPNngbwzACV2ivm+id9wq7PtsBQ7/v7+ZcYoJSADiZncnbH/2BvYU7SAurwCVClN3DSFcnru9xM7eOv5/IiDaNKjvE5h0ZF+ZRnlywvMEB6aHo+RSUnmdg/IhG1W8YRmCKSZ5G4rqX2FL4qb+b8gUmKPnJp8d2s2Lbi+wv3UtGqAuPCF3tHsZXxTK2z63MGvttQkPDvnI9o/rPYtm+rdwTOZmI8MgGb79w5s+/chsMwwg8nXoPoZfTzmrKyC3PJToi2t9NAkxQuqb2H97Kqh0vsb/8IJlh3lkSeogyw92bCQPuZMqorzfq0tqV3Dh0FlsTJxEeFtGk5RqG0cyJ0N4RD5zm0IU0xscFxn0lE5SusoKiC7y64Zd8UvAR6WFuAHoLzPX0Y3rSNxk7bPZVb4MJSIZh1KZH7ATk4qt8nPm+CUrB7uSZTF5a751lodhuo5tNmav9mTP8e4wcPNnfzTMMwyB++Gx6bniFjOxUfzflEhOUmpjTWcn/vXUf/3HupMxuI6WiNTfH3c3tE+5v8ktzhmEYX0XnngOIdzrY7jiL2+P2PkLiZz7NEyMi00UkU0SyRORntXweJiL/sj7fISK9qn32qJWeKSLT6itTRHpbZRyxygxt6jqullPZR1j4txv4Z9Vu+rrCeGHQr/jrfTu4Y/IPTEAyDCMg9Y0YTIlN2Xpks7+bAvgQlETEDrwIzAASgTtFJLFGtkVAgarGA88Ci61tE4H5wEBgOvBHEbHXU+Zi4FlVTQAKrLKbuo4md/LsYe5bfSuZoU6+GTaW1xft5KbhX572xzAMI5CMHfotbKqsSV3q76YAvp0pjQSyVPWYqjqBZUDNo+1c4O/W8nJgknjfYTAXWKaqlap6HMiyyqu1TGubiVYZWGXe0pR1+NYtDVNaVsyDq+dx3gGPxH6Hn87/kzkzMgyjWUhKmsyQSgcfVB3i4JHt/m6OT/eUYoFT1dZPA6PqyqOqVSJSBHS00rfX2DbWWq6tzI5AoapW1ZK/qer4EhG5F7jXWi0RkTwgt7a89ZnPg8znwcZsGoiiaWQ/BCHTF5eZvvAKun4Ywg2N3TQa6NkUbfAlKNX2Nh71MU9d6bWdoV0pf1PW8eVE1SXAks/XRWSXqqbUlrclMf1wmemLy0xfeJl+uMzqi15NUZYvl+9OAz2qrXcHztaVR0QcQDsg/wrb1pWeC7S3yqhZV1PVYRiGYQQoX4LSTiDBGhUXindQwaoaeVYBC63lecAmVVUrfb41cq43kACk1lWmtc1mqwysMv/TlHX41i2GYRiGP9R7+c66f/MDYD1gB15R1TQReQrYpaqrgJeB10QkC+/Zy3xr2zQReRNIB6qAB1TVDVBbmVaVjwDLRORXwF6rbJq4jvosqT9Li2D64TLTF5eZvvAy/XBZk/WFeE82DMMwDMP/fHp41jAMwzCuBROUDMMwjIBhglI113paIn8QkVdEJEdEDlVL6yAiG62pnTaKSJSVLiLyB6s/DojIsGrbLLTyHxGRhbXVFchEpIeIbBaRDBFJE5EfW+ktsS/CRSRVRPZbffGkld5kU341J9aMMHtFZLW13lL74YSIHBSRfSKyy0q7+t8PVTU/3vtqduAo0AcIBfYDif5u11XYz3HAMOBQtbTfAD+zln8GLLaWbwbW4X0W7Hpgh5XeAThm/Y6ylqP8vW8N7IdMVJ2IAAAC5klEQVQYYJi13AY4jHc6qpbYFwK0tpZDgB3WPr4JzLfSXwLut5a/D7xkLc8H/mUtJ1rfmzCgt/V9svt7/xrRH/8FvAGsttZbaj+cAKJrpF3174c5U7rsmk1L5E+q+hHe0YvVVZ/CqebUTq+q13a8z5DFANOAjaqar6oFwEa88w42G6qarap7rOViIAPvTCAtsS9UVUus1RDrR2m6Kb+aDRHpDswEllrrTTn1WTC46t8PE5Quq206pdg68gabLqqaDd6DNdDZSq+rT4Kqr6zLLkPxniG0yL6wLlntA3LwHjiO4uOUX0D1Kb+ae188BzwMeKx1n6c+I7j6Abx/mGwQkd3inYoNrsH3w7xP6TJfplNqaRo6tVOzIyKtgbeBn6jqRe8furVnrSUtaPpCvc/2JYtIe2AFMKC2bNbvoOwLEZkF5KjqbhEZ/3lyLVmDuh+qGaOqZ0WkM7BRRD69Qt4m6wtzpnRZS56W6Lx1qo31O8dKD+opnEQkBG9A+oeq/ttKbpF98TlVLQQ+wHtfoKmm/GouxgBzROQE3sv3E/GeObW0fgBAVc9av3Pw/qEykmvw/TBB6bKWPC1R9Smcak7tdI81suZ6oMg6ZV8PTBWRKGv0zVQrrdmwrv2/DGSo6jPVPmqJfdHJOkNCRCKAyXjvsTXVlF/Ngqo+qqrd1Tux6Hy8+3UXLawfAEQkUkTafL6M9//1Ia7F98PfIzwC6QfvCJLDeK+n/9zf7blK+/hPIBtw4f0rZhHe6+DvA0es3x2svIL3RYlHgYNASrVyvo33Bm4W8C1/71cj+mEs3ssIB4B91s/NLbQvhuCd0uuAdeB5wkrvg/dgmgW8BYRZ6eHWepb1eZ9qZf3c6qNMYIa/9+0r9Ml4Lo++a3H9YO3zfusn7fPj4bX4fphphgzDMIyAYS7fGYZhGAHDBCXDMAwjYJigZBiGYQQME5QMwzCMgGGCkmEYhhEwTFAyDMMwAoYJSoZhGEbA+P8z9lQSUWvHZgAAAABJRU5ErkJggg==\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], "source": [ "plt.clf()\n", "# plt.plot(x_part, calcs, '.')\n", @@ -860,7 +915,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ @@ -876,7 +931,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": {}, "outputs": [], "source": [ @@ -892,7 +947,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": {}, "outputs": [], "source": [ @@ -905,7 +960,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, "metadata": {}, "outputs": [], "source": [ @@ -962,7 +1017,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, "metadata": {}, "outputs": [], "source": [ @@ -1046,7 +1101,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 19, "metadata": {}, "outputs": [], "source": [ @@ -1055,7 +1110,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, "metadata": {}, "outputs": [], "source": [ @@ -1064,7 +1119,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 21, "metadata": {}, "outputs": [], "source": [ @@ -1073,7 +1128,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 22, "metadata": { "scrolled": false }, @@ -1121,7 +1176,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, "metadata": {}, "outputs": [], "source": [ @@ -1138,7 +1193,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 24, "metadata": {}, "outputs": [], "source": [ @@ -1162,7 +1217,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 25, "metadata": {}, "outputs": [], "source": [ @@ -1189,7 +1244,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 26, "metadata": {}, "outputs": [], "source": [ @@ -1212,7 +1267,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 27, "metadata": {}, "outputs": [], "source": [ @@ -1221,7 +1276,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, "metadata": {}, "outputs": [], "source": [ @@ -1237,7 +1292,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 29, "metadata": {}, "outputs": [], "source": [ @@ -1267,7 +1322,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 30, "metadata": {}, "outputs": [], "source": [ @@ -1281,7 +1336,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 31, "metadata": {}, "outputs": [], "source": [ @@ -1299,7 +1354,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, "metadata": {}, "outputs": [], "source": [ @@ -1313,7 +1368,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 33, "metadata": {}, "outputs": [], "source": [ @@ -1334,7 +1389,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 34, "metadata": {}, "outputs": [], "source": [ @@ -1344,7 +1399,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 35, "metadata": {}, "outputs": [], "source": [ @@ -1375,7 +1430,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 36, "metadata": {}, "outputs": [], "source": [ @@ -1392,7 +1447,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 37, "metadata": {}, "outputs": [], "source": [ @@ -1528,7 +1583,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 38, "metadata": {}, "outputs": [], "source": [ @@ -1607,7 +1662,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 39, "metadata": { "scrolled": false }, @@ -1818,7 +1873,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "metadata": {}, "outputs": [], "source": [ @@ -1830,7 +1885,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 41, "metadata": {}, "outputs": [], "source": [ @@ -1842,7 +1897,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 42, "metadata": {}, "outputs": [], "source": [ @@ -1857,7 +1912,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 43, "metadata": {}, "outputs": [], "source": [ @@ -1866,7 +1921,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 44, "metadata": {}, "outputs": [], "source": [ @@ -1875,7 +1930,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 45, "metadata": {}, "outputs": [], "source": [ @@ -1884,16 +1939,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "# BR_steps = np.linspace(0.0, 1e-3, 11)\n", "pull_dic = {}\n", "\n", + "# mi = 1e-4\n", + "# ma = 6e-4\n", + "# ste = 6\n", + "\n", "mi = 1e-4\n", - "ma = 6e-4\n", - "ste = 6\n", + "ma = 3e-3\n", + "ste = 20\n", "\n", "for param in total_f_fit.get_dependents():\n", " if param.floating:\n", @@ -1918,7 +1977,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 47, "metadata": {}, "outputs": [], "source": [ @@ -1938,15 +1997,33 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 48, "metadata": { "scrolled": true }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0. 0.00025263 0.00040526 0.00055789 0.00071053 0.00086316\n", + " 0.00101579 0.00116842 0.00132105 0.00147368 0.00162632 0.00177895\n", + " 0.00193158 0.00208421 0.00223684 0.00238947 0.00254211 0.00269474\n", + " 0.00284737 0.003 ]\n", + "[0. 0.24525574 0.31063037 0.36446136 0.41130637 0.45333628\n", + " 0.49178719 0.5274424 0.5608354 0.59234888 0.62226847 0.65081403\n", + " 0.67815909 0.70444347 0.72978178 0.75426939 0.77798661 0.80100188\n", + " 0.82337407 0.84515425]\n", + "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" + ] + } + ], "source": [ "# zfit.run.numeric_checks = False \n", "\n", - "load = False\n", + "load = True\n", "\n", "bo = True\n", "\n", @@ -1971,7 +2048,7 @@ "nevents = int(pdg[\"number_of_decays\"]*cut_BR)\n", "# nevents = pdg[\"number_of_decays\"]\n", "event_stack = 1000000\n", - "nevents *= 41\n", + "# nevents *= 41\n", "# zfit.settings.set_verbosity(10)\n", "\n", "# mi = 1e-4\n", @@ -2104,9 +2181,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 49, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number of jobs: 562\n" + ] + } + ], "source": [ "if load:\n", " \n", @@ -2182,7 +2267,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 50, "metadata": {}, "outputs": [], "source": [ @@ -2243,7 +2328,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 51, "metadata": {}, "outputs": [], "source": [ @@ -2259,65 +2344,158 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 52, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(20, 562)\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAEWCAYAAAB/tMx4AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAXoklEQVR4nO3debRkZX3u8e8jgihDmBpkbo1oMEbQtKiXxBhQFwgqriBO8SKBYK5xqYlDiN4bTZYazKBeozeGONDrCgo4gdONiGCMA9ogqAgqElRopJuhGQQjjb/7x96NxaFOnzpDneq3z/ezVq+u2vXW3r9dtc9T7373rl2pKiRJ7bnfpAuQJM2NAS5JjTLAJalRBrgkNcoAl6RGGeCS1CgDfARJliepJPfv71+Q5IRJ16XZS/LkJNdMuo7FluRNSW5I8tOp2/MCL+d3k3xvoec7H/26nzrpOsZhSQV4kquT3Jnk9iTXJ/lAkm0XeBlvTHJXktv6f99P8q4kuw+0eXKSX/Z13J7kmiRnJnnciMs4NcmbFrLucUpyUJLPJFmX5KYkX09yXP/YfQK1fw0/OJlq564PxvOT3JHkiiRP2UjbnZKc0YfqDUlOS7L9wOOD2+rtST43j7r2Bl4FPLKqHjzX+Uwz70rysA33q+pLVfWIhVzGwLIuSPLzgdfk9iRPHMeyWrGkArz3jKraFngs8Djgf45hGWdU1XbATsCzgQcDFw2GOLC6r2M74AnAFcCXkhw6hnruZRw9r40s64nAF4AvAg8Ddgb+B3D4YtWwiD4EfJNuHV8PfCTJsmnavgnYEXgo8OvAbsAbp7R5RlVt2/972jzq2he4sarWzGMem4qXDbwm21bVVydd0CQtxQAHoKquBT4LPAru6fHc02NaiF5gVd1VVZcBzwXW0vWCprapqrqmqv4KeC/w1n75SfL2JGuS3JLkW0keleRE4IXAa/seyCf79icl+WHf6/9ukmcPrMuLk3y5n99N3DcoGNL2n/rlXjHPD5W/B1ZW1Vur6oZ+fS+qqmOSbEP3Huwx0KN6AfA64Ln9/UuH1HhSko9Mmfa/k7yzv31cksv71+KqJC/ZyPreqwc5de8myZFJLun3Hr6S5NHTzOfhdJ2CN1TVnVX1UeDbwB9Ms+iHAJ+oqlur6hbg48BvTlfnXPXb9Ln86jU+dUibPZKc0+8dXZnkjwceOyjJV/v1v67fm9yqf+zf+2aX9vN+7tQ9qv7v6tX99ntLv9ex9cDjr+3nuzrJCVPfj1ms57vS7cnemuQbSf7bNO0elOT0JDf26/T1JLv0j+2Qbq/8un5ef5Nkk87ITbq4cep3K59O12Maq6q6Gzgb+N0Zmn4MeGwfbE8DngQ8HNiB7kPgxqo6BTgN+Lu+B/KM/rk/7Of/a8BfAx+c0uN/PHAVsCvw5hnq2NB2F+ANwMeS7DTKug5K8iDgicBHhj1eVT+j64mvHuhRnQ68hW4vZtuqOmDIUz8EPD39kEOSLYBjgNP7x9cARwLbA8cBb0/y2DnU/1jg/cBL6HrV/wKck+QBQ5r/JnBVVd02MO1Spg/ldwNHJtkxyY50Qf/ZKW1OS7I2yeeSDHsdZlRVn+fer/GLhzT7EHANsAdwNPCWgQ/tu4E/o9sWnggcCry0n/eT+jYH9PM+Y5oyjgEOo/vQejTwYoAkhwF/DjyFbu/s9+ayjr0L+3nvRLe9nTXN+3Qc8CBgL7r39KXAz/vHPgjcSbdHtAI4om+/yVqKAf6JJOuA/6DbrX/LIi13Nd3GNVOb0AX2XXTDK78BpKour6rrpntiVZ1VVaur6pf9H9IPgIMG511V/1RV66vqzhnqWAO8o9+DOAP4Ht3GPFs70m1j09Y9F1X1I+Bi4Kh+0iHAHVX1tf7xT1fVD/ve/heBzzHzh+cwfwz8S1VdWFV3V9VK4L/ohrym2ha4Zcq0W+jew2EuBrYCbuz/3Q38n4HHXwgspxv+OB/4tyQ7zGEdNqrvyPwO8BdV9fOquoRuT/BFAP3e0tf67eZqug+x2QbtO/tt8ybgk8CB/fRjgA9U1WVVdQddx2PGefU953VJLt4wsar+b1XdVFXrgb+j+/Ae1pO/i+7D6GH9e7qqqm5Psifdh9OfVdUdVfVT4B3A82a5rotqKQb4UVW1Q1XtW1UvHSHMFsqewE0jtClgXVV9AXgXXU/t+iSnZOAg11RJ/vvArv46uqGhXQaa/GQWtV5b977K2Y/oemdTl/nCgaGPqb1HgJuBXwK7D3lsvk4Hnt/ffgG/6n2T5PAkX+uHBNbR7WntMmQeM9kXeNVAYKwD9mbIawHcThcag7YHbhvSFuAs4Pt0Ab893R7UPUN2VfXlfijmjqr6W2AdQz6Ekuwz8B7cPsv1g25dbpqy5/Ajum2RJA9P8ql0Z6/cStfhme1r+dOB23fQfdhtWPbgdjnKNvry/u93h6q6Z6+qH4q5IsktdNvdNtPUeSrweeDMJNcmOTndMaF9gQfQ/a1teK/fTXdsYpO1FAN8Oj+j27XaYMGO1vfjaM8AvjRD02cDF/dDC1TVO6vqt+l2wx8OvKZvd69LSCbZF/hX4GXAzlW1A/Adut48w54zgz2TDD53H7q9g3upqtMGhj7uc1Cy71V9lenHgaera5RazwKenGQvutftdIB+t/mjwD8Au/WvxWe492sx6A6mf99/Arx5IDB2qKoHVdWHhsznMuChSQZ73Af004c5gK53/7Oquh14D90HzXRq2DpU1Y8HD+pt5PnTWQ3sNKXufYBr+9v/THeAfb+q2p7u+MR0r+VsXUc3lLHB3nOZSZLfpxuK+QO6vdcd6T5Qh71ev6iqN1bV/nR7Hs+m29v5Cd22sNPAe719VQ095rGpMMB/5RLgeUm2TLKCbixwXvp57U83xvhg4G1D2iTJnkneAJxA9wdCkscleXySLek+XH5Ot5sNcD3d2QsbbEP3B762f+5x9Adn52hX4OV9/c8B9qcLwbl4LfDiJK9JsnNf3wFJPtw/fj2wc5JfG3jO9cDyjR1Aqqq1wAXAB4D/rKrL+4e2outJrQXWJzmc7njCdC4BXpBki35MdnB44F+BP+nfhyTZJskRU8JuQz3f7+f1hiRbpzuI/Gi6D5NhvgGckOSBSR4InEg3Zr6hV31wkq36eb2Grjf55Y2sx5xU1U+ArwB/2y/r0cDxdMdZoNtDuBW4Pclv0J1BNGjqtjgbZwLHJdm/P17yV3Ocz3bAeuAGYEu6g/TbDGuY5JB0JwPcj2697gLu7l+HLwL/kGT7JPdL8rAkTxo2n02FAf4r/4vu4MXNdGNxp2+8+UY9t9+dXQecQzfG+dtVNdiL3aNvczvdH/NvAU+uqg3n+25PFyA30+3S3kjXqwR4H/DIflfvE1X1XeAf6Xq71/fzms8f+4XAfnR/EG8Gjq6qG+cyo6r6Ct0Y9SHAVenOgjmF/gOhqq6g+4C7ql+fPeh61wA3Do5zDnE63QGwe96rfijg5XThcDPd8Mo5G5nHK+j2jtbR9cQ+MTCvVXTj4O/q53Ul/QG4aTyP7uDXzcDJdK/bhg/VFyYZ7I3/Ed0Y9zV0vd2HDsx7O7qe7839Y4cBh8/1PRjB8/taVtOdDfOGqjq3f+zVdK/hbXTb49QDlW8EVvbv3TGzWWhVfRZ4J90Y/5V02y90xxlm4zN0wyI/AK6mC+bpjrvsQXeywK10e0efp9v+AP6QLvi/S/fan8UC7omPQ8ofdNCAJC8GTqiq35l0LVpa+r3V7wAP6A9Gagb2wCVNTJJn90NFO9J9B+KThvfoDPAlKMl7cu+vI2/4955J16Yl5yV0xyt+SHeMZ+oYuzbCIRRJapQ9cElq1KJd1Ahgl112qeXLly/mIiWpeRdddNENVXWfC6MtaoAvX76cVatWLeYiJal5SX40bLpDKJLUKANckhplgEtSowxwSWqUAS5JjTLAJalRBrgkNcoAl6RGGeCS1KhF/SamNl/LT/r00OlXnzyX30KWNAp74JLUKANckhplgEtSoxwD11g5Ni6Njz1wSWqUAS5JjTLAJalRBrgkNcoAl6RGGeCS1CgDXJIaNdJ54EmuBm4D7gbWV9WKJDsBZwDLgauBY6rq5vGUKUmaajY98N+vqgOrakV//yTgvKraDzivvy9JWiTzGUJ5FrCyv70SOGr+5UiSRjVqgBfwuSQXJTmxn7ZbVV0H0P+/67AnJjkxyaokq9auXTv/iiVJwOjXQjm4qlYn2RU4N8kVoy6gqk4BTgFYsWJFzaFGSdIQI/XAq2p1//8a4OPAQcD1SXYH6P9fM64iJUn3NWOAJ9kmyXYbbgNPA74DnAMc2zc7Fjh7XEVKku5rlCGU3YCPJ9nQ/vSq+n9JvgGcmeR44MfAc8ZXppYKLz8rjW7GAK+qq4ADhky/ETh0HEVJkmbmNzElqVEGuCQ1ygCXpEYZ4JLUKANckhplgEtSowxwSWqUAS5JjTLAJalRBrgkNcoAl6RGGeCS1CgDXJIaZYBLUqMMcElqlAEuSY0ywCWpUQa4JDXKAJekRhngktQoA1ySGmWAS1KjDHBJapQBLkmNMsAlqVEGuCQ1ygCXpEYZ4JLUKANckhp1/1EbJtkCWAVcW1VHJnkI8GFgJ+Bi4EVV9YvxlKnNzfKTPj3pEqTmzaYH/grg8oH7bwXeXlX7ATcDxy9kYZKkjRspwJPsBRwBvLe/H+AQ4CN9k5XAUeMoUJI03Kg98HcArwV+2d/fGVhXVev7+9cAew57YpITk6xKsmrt2rXzKlaS9CszBniSI4E1VXXR4OQhTWvY86vqlKpaUVUrli1bNscyJUlTjXIQ82DgmUmeDmwNbE/XI98hyf37XvhewOrxlSlJmmrGHnhV/WVV7VVVy4HnAV+oqhcC5wNH982OBc4eW5WSpPuYz3ngfwH8eZIr6cbE37cwJUmSRjHyeeAAVXUBcEF/+yrgoIUvSZI0Cr+JKUmNMsAlqVEGuCQ1ygCXpEYZ4JLUKANckhplgEtSowxwSWqUAS5JjTLAJalRBrgkNcoAl6RGGeCS1CgDXJIaZYBLUqMMcElqlAEuSY0ywCWpUQa4JDXKAJekRhngktSoWf0qvZa25Sd9etIlSBpgD1ySGmWAS1KjDHBJapQBLkmNMsAlqVEGuCQ1ygCXpEZ5HriWlOnOZb/65CMWuRJp/mbsgSfZOsnXk1ya5LIkf91Pf0iSC5P8IMkZSbYaf7mSpA1GGUL5L+CQqjoAOBA4LMkTgLcCb6+q/YCbgePHV6YkaaoZA7w6t/d3t+z/FXAI8JF++krgqLFUKEkaaqSDmEm2SHIJsAY4F/ghsK6q1vdNrgH2nOa5JyZZlWTV2rVrF6JmSRIjBnhV3V1VBwJ7AQcB+w9rNs1zT6mqFVW1YtmyZXOvVJJ0L7M6jbCq1gEXAE8Adkiy4SyWvYDVC1uaJGljRjkLZVmSHfrbDwSeAlwOnA8c3Tc7Fjh7XEVKku5rlPPAdwdWJtmCLvDPrKpPJfku8OEkbwK+CbxvjHVKkqaYMcCr6lvAY4ZMv4puPFySNAF+lV6SGmWAS1KjDHBJapQBLkmNMsAlqVEGuCQ1ygCXpEYZ4JLUKANckhplgEtSowxwSWqUAS5JjTLAJalRo1xOVkvM8pM+PekS7mO6mq4++YhFrkTadNgDl6RGGeCS1CgDXJIaZYBLUqMMcElqlAEuSY0ywCWpUQa4JDXKAJekRhngktQov0ovLRIvB6CFZg9ckhplgEtSowxwSWqUY+BL2KZ42VhJo5uxB55k7yTnJ7k8yWVJXtFP3ynJuUl+0P+/4/jLlSRtMMoQynrgVVW1P/AE4E+TPBI4CTivqvYDzuvvS5IWyYwBXlXXVdXF/e3bgMuBPYFnASv7ZiuBo8ZVpCTpvmZ1EDPJcuAxwIXAblV1HXQhD+w6zXNOTLIqyaq1a9fOr1pJ0j1GDvAk2wIfBV5ZVbeO+ryqOqWqVlTVimXLls2lRknSECMFeJIt6cL7tKr6WD/5+iS794/vDqwZT4mSpGFGOQslwPuAy6vqbQMPnQMc298+Fjh74cuTJE1nlPPADwZeBHw7ySX9tNcBJwNnJjke+DHwnPGUKE1vU7u+iOfWazHNGOBV9R9Apnn40IUtR5I0Kr9KL0mNMsAlqVEGuCQ1ygCXpEYZ4JLUKANckhrl9cAlZn/+tr9jqU2BPXBJapQBLkmNcghFmoPF+Mr8pnaZAG167IFLUqMMcElqlAEuSY0ywCWpUQa4JDXKAJekRhngktQoA1ySGmWAS1KjDHBJapQBLkmNMsAlqVEGuCQ1ygCXpEYZ4JLUKANckhplgEtSowxwSWqUAS5JjZrxNzGTvB84ElhTVY/qp+0EnAEsB64Gjqmqm8dXpjQ7i/GbldKkjdIDPxU4bMq0k4Dzqmo/4Lz+viRpEc0Y4FX178BNUyY/C1jZ314JHLXAdUmSZjDjEMo0dquq6wCq6roku07XMMmJwIkA++yzzxwXJ22+HO7RXI39IGZVnVJVK6pqxbJly8a9OElaMuYa4Ncn2R2g/3/NwpUkSRrFXAP8HODY/vaxwNkLU44kaVQzBniSDwFfBR6R5JokxwMnA09N8gPgqf19SdIimvEgZlU9f5qHDl3gWiRJs+A3MSWpUQa4JDVqrueBS5qQ6c4bv/rkIxa5Ek2aPXBJapQBLkmNMsAlqVGOgW9GHBvVMLO91orbSzvsgUtSowxwSWqUAS5JjTLAJalRBrgkNcoAl6RGGeCS1CjPA18C/M1FafNkD1ySGmWAS1KjUlWLtrAVK1bUqlWrFm15m5rZftXdoQ9tSvyK/eQkuaiqVkydbg9ckhplgEtSowxwSWqUpxFKGomXpd302AOXpEYZ4JLUKANckhq15MbAF+Nc7NmO/Xm+t6S5sAcuSY0ywCWpUQa4JDVqsx0Dn+248kKOQzumLW3cbI9FjXv+465nXObVA09yWJLvJbkyyUkLVZQkaWZzDvAkWwDvBg4HHgk8P8kjF6owSdLGzacHfhBwZVVdVVW/AD4MPGthypIkzWTO1wNPcjRwWFWd0N9/EfD4qnrZlHYnAif2dx8BfG/u5U7ELsANky5ikbnOS4Pr3I59q2rZ1InzOYiZIdPu82lQVacAp8xjOROVZNWwC6lvzlznpcF1bt98hlCuAfYeuL8XsHp+5UiSRjWfAP8GsF+ShyTZCngecM7ClCVJmsmch1Cqan2SlwH/BmwBvL+qLluwyjYdzQ7/zIPrvDS4zo1b1B81liQtHL9KL0mNMsAlqVEG+CwkeXWSSrLLpGsZtyR/n+SKJN9K8vEkO0y6pnFZapeESLJ3kvOTXJ7ksiSvmHRNiyHJFkm+meRTk65loRjgI0qyN/BU4MeTrmWRnAs8qqoeDXwf+MsJ1zMWS/SSEOuBV1XV/sATgD9dAusM8Arg8kkXsZAM8NG9HXgtQ76stDmqqs9V1fr+7tfozvPfHC25S0JU1XVVdXF/+za6UNtzslWNV5K9gCOA9066loVkgI8gyTOBa6vq0knXMiF/BHx20kWMyZ7ATwbuX8NmHmaDkiwHHgNcONlKxu4ddB2wX066kIW02V4PfLaSfB548JCHXg+8Dnja4lY0fhtb56o6u2/zerpd7tMWs7ZFNNIlITZHSbYFPgq8sqpunXQ945LkSGBNVV2U5MmTrmchGeC9qnrKsOlJfgt4CHBpEuiGEi5OclBV/XQRS1xw063zBkmOBY4EDq3N9wsDS/KSEEm2pAvv06rqY5OuZ8wOBp6Z5OnA1sD2ST5YVX844brmzS/yzFKSq4EVVdXiFc1GluQw4G3A71XV2knXMy5J7k93kPZQ4Fq6S0S8YDP9VjEA6XoiK4GbquqVk65nMfU98FdX1ZGTrmUhOAau6bwL2A44N8klSd4z6YLGoT9Qu+GSEJcDZ27O4d07GHgRcEj/3l7S907VGHvgktQoe+CS1CgDXJIaZYBLUqMMcElqlAEuSY0ywLUkJLm7P13uO0nOSvKgGdqfmuTo/vYFSTabH8LV5sMA11JxZ1UdWFWPAn4B/MmkC5LmywDXUvQl4GFJlif5zoaJ/fXe3zi5sqTZMcC1pPRfnT8c+Paka5HmywDXUvHAJJcAq+h+lON9E65HmjevRqil4s6qOnBwQpL13LsTs/XiliTNjz1wLWXXA7sm2TnJA+gunSs1wx64lqyquivJ39D9Gs1/AldMuCRpVrwaoSQ1yiEUSWqUAS5JjTLAJalRBrgkNcoAl6RGGeCS1CgDXJIa9f8B1a7sCd9Z/TYAAAAASUVORK5CYII=\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], "source": [ - "# l = []\n", + "l = []\n", "\n", "\n", - "# if load:\n", - "# CLs_values = -1*np.array(CLs_list)\n", + "if load:\n", + " CLs_values = -1*np.array(CLs_list)\n", "\n", - "# if not os.path.exists('data/CLs/plots'):\n", - "# os.mkdir('data/CLs/plots')\n", - "# print(\"Directory \" , 'data/CLs/plots' , \" Created \")\n", + "if not os.path.exists('data/CLs/plots'):\n", + " os.mkdir('data/CLs/plots')\n", + " print(\"Directory \" , 'data/CLs/plots' , \" Created \")\n", "\n", - "# print(np.shape(CLs_values))\n", + "print(np.shape(CLs_values))\n", " \n", - "# for step in range(1,ste):\n", - "# plt.clf()\n", - "# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step]))\n", - "# plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0')\n", - "# plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating')\n", - "# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted')\n", - "# plt.legend()\n", - "# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step]))\n", + "for step in range(1,ste):\n", + " plt.clf()\n", + " plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step]))\n", + " plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0')\n", + " plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating')\n", + " plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted')\n", + " plt.legend()\n", + " plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step]))\n", " \n", - "# l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0]))\n", + " l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0]))\n", " \n", - "# for step in range(2*ste):\n", - "# if step%2 == 0:\n", - "# floaty = True\n", - "# else:\n", - "# floaty = False\n", - "# for key in pull_dic.keys():\n", - "# if not os.path.exists('data/CLs/plots/{}'.format(key)):\n", - "# os.mkdir('data/CLs/plots/{}'.format(key))\n", - "# plt.clf()\n", - "# plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty))\n", - "# plt.hist(pull_dic[key][step], bins = 50, range = (-5,5))\n", - "# plt.xlabel('Pull')\n", - "# plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty))\n" + "for step in range(2*ste):\n", + " if step%2 == 0:\n", + " floaty = True\n", + " else:\n", + " floaty = False\n", + " for key in pull_dic.keys():\n", + " if not os.path.exists('data/CLs/plots/{}'.format(key)):\n", + " os.mkdir('data/CLs/plots/{}'.format(key))\n", + " plt.clf()\n", + " plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty))\n", + " plt.hist(pull_dic[key][step], bins = 50, range = (-5,5))\n", + " plt.xlabel('Pull')\n", + " plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty))" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 69, "metadata": { "scrolled": false }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "BR: 0.0003\n", + "0.7112299465240641\n", + "\n", + "BR: 0.0004\n", + "0.6176470588235294\n", + "\n", + "BR: 0.0006\n", + "0.5401069518716578\n", + "\n", + "BR: 0.0007\n", + "0.44385026737967914\n", + "\n", + "BR: 0.0009\n", + "0.339572192513369\n", + "\n", + "BR: 0.0010\n", + "0.31016042780748665\n", + "\n", + "BR: 0.0012\n", + "0.23796791443850268\n", + "\n", + "BR: 0.0013\n", + "0.21122994652406418\n", + "\n", + "BR: 0.0015\n", + "0.17647058823529413\n", + "\n", + "BR: 0.0016\n", + "0.1443850267379679\n", + "\n", + "BR: 0.0018\n", + "0.10695187165775401\n", + "\n", + "BR: 0.0019\n", + "0.10695187165775401\n", + "\n", + "BR: 0.0021\n", + "0.0855614973262032\n", + "\n", + "BR: 0.0022\n", + "0.05080213903743316\n", + "\n", + "BR: 0.0024\n", + "0.045454545454545456\n", + "\n", + "BR: 0.0025\n", + "0.045454545454545456\n", + "\n", + "BR: 0.0027\n", + "0.026737967914438502\n", + "\n", + "BR: 0.0028\n", + "0.034759358288770054\n", + "\n", + "BR: 0.0030\n", + "0.03208556149732621\n", + "\n" + ] + } + ], "source": [ - "# for s in range(len(l)):\n", - "# print('BR: {:.4f}'.format(BR_steps[s+1]))\n", - "# print(2*l[s]/len(CLs_values[s]))\n", - "# print()" + "for s in range(len(l)):\n", + " print('BR: {:.4f}'.format(BR_steps[s+1]))\n", + " print(l[s]/len(np.where(np.array(CLs_values[0]) < np.mean(CLs_values[0]))[0]))\n", + " print()\n", + "# print(l[s], len(CLs_values[s]))\n", + "# print()\n", + "# print(len(CLs_values[0])/2)\n", + "# print(len(np.where(np.array(CLs_values[0]) < np.mean(CLs_values[0]))[0]))\n", + "# plt.clf()\n", + "# # plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty))\n", + "# plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0')\n", + "# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted')\n", + "# plt.show()" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 54, "metadata": {}, "outputs": [], "source": [ @@ -2328,7 +2506,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 55, "metadata": {}, "outputs": [], "source": [ @@ -2339,16 +2517,24 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 56, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 min, 44 s\n" + ] + } + ], "source": [ "print(display_time(int(time.time()-start)))" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 57, "metadata": {}, "outputs": [], "source": [ diff --git a/__pycache__/pdg_const1.cpython-37.pyc b/__pycache__/pdg_const1.cpython-37.pyc index 9128726..3b22672 100644 --- a/__pycache__/pdg_const1.cpython-37.pyc +++ b/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316796/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e871055 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316796/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..45b9eb0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e731579 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e914522 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..39c6234 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d0c81c9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..582fed6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316796/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316796/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316796/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316796/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316796/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316798/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..781066c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316798/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f651645 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..15634b9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f63bd07 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..29868d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d208218 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c3387b5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316798/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316798/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316798/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316798/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316798/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316805/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1f76398 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316805/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0f0bb58 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..470a61b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1135a90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..03fea97 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cda9745 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ddb47ff --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316805/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316805/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316805/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316805/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316805/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316807/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b4a6f94 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316807/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..55de09a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..33caf7e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0ca1de6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0bce08a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..263b655 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7460f6b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316807/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316807/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316807/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316807/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316807/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316808/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..81a9de4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316808/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..be64f46 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..84a7824 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..62b619e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..260c005 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c32131f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..04b9cef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316808/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316808/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316808/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316808/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316808/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316809/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..05bd418 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316809/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e814e5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..279cbe6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f224ddb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1a41b06 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d08c890 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0b3c0c2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316809/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316809/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316809/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316809/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316809/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316810/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..21cb0e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316810/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..36b3539 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e756e59 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..042dcde --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..312353d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bd1619b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ffa1fb2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316810/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316810/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316810/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316810/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316810/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316811/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6e0fb5c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316811/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..eae3ebd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..486e296 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..671ba39 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c174305 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..caee4ee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..400edc9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316811/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316811/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316811/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316811/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316811/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316812/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fba4cbb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316812/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..7f69fde --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..229c22d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..08cdb94 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7d20fa8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..298db7c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4c9028a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316812/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316812/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316812/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316812/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316812/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316813/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..66dd127 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316813/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..492be3e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c43d769 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6b760fd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e074910 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ed84595 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4a60cd8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316813/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316813/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316813/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316813/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316813/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316814/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4956c29 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316814/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c3bc301 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4662a7e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..aa1508e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fbf3feb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bddef3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e1623e4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316814/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316814/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316814/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316814/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316814/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316815/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..55eada2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316815/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3bc372e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fc9c577 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b113007 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9d2aa8c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ba9d095 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..501ed66 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316815/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316815/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316815/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316815/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316815/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316816/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..97784b9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316816/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..09624cf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..832168a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..86b1b5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..513b83a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3f96e21 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2e390e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316816/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316816/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316816/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316816/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316816/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316817/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..706e4bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316817/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6793039 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..dd3f9c6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f5089c5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..022977a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5207739 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3185b69 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316817/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316817/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316817/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316817/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316817/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316818/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f461c0f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316818/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5d43a45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f99a203 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fcfbe15 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d963939 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c359bb0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5cb186d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316818/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316818/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316818/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316818/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316818/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316819/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..908fa05 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316819/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8a7e6a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e0593c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f1c3ce0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..80e5983 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..957843f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..78131f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316819/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316819/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316819/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316819/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316819/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316820/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b8f6607 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316820/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bf63269 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a09e14d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c6938d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..625ef3b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1d33b87 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b0989d2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316820/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316820/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316820/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316820/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316820/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316821/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fb0323f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316821/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ec0213f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ea166e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..21161ea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1557091 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..199e664 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e9061d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316821/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316821/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316821/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316821/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316821/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316822/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..96f3309 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316822/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..dece191 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..aa7abb0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4ad36ff --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ff7de0f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3a390d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5f1a03c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316822/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316822/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316822/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316822/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316822/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316823/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f2ce409 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316823/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5c37bfa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..edbcdcd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..af529a8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..bf8bd6e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..330a16a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d3261ed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316823/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316823/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316823/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316823/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316823/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316824/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b7e681c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316824/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bb55b55 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..70d3f85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..74e7716 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..72468fa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e0f9d85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d1a9c57 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316824/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316824/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316824/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316824/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316824/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316825/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..03b3435 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316825/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e536c00 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4e72885 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0c73a28 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..edd3dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7b0d471 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..56bf961 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316825/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316825/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316825/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316825/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316825/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316826/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..70be6eb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316826/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..974d504 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..95311e3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4b312e6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b814dee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a972674 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7be58fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316826/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316826/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316826/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316826/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316826/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316827/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..51334e5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316827/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3909da2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..73052e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..cd8a314 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7831310 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d966842 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..658f29a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316827/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316827/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316827/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316827/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316827/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316828/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..201f9c4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316828/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..951da15 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..64a29f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..365cfe0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6357299 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c03de40 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9b684d9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316828/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316828/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316828/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316828/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316828/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316829/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b81b054 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316829/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0b0e00b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1412db6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ed02de7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..070e74f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..293c52d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..030b733 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316829/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316829/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316829/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316829/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316829/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316830/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4243e5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316830/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..716959d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a1106a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e4ded8f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d63668e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1103a5e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0dabae8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316830/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316830/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316830/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316830/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316830/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316831/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..67c1d5d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316831/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9bfebab --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..333907a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a87f8ca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6433320 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8a5d950 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..af13141 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316831/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316831/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316831/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316831/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316831/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316832/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c8b2912 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316832/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9e24844 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5505136 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..26514ea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..33ef789 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..725bf8c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..94ce10b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316832/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316832/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316832/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316832/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316832/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316833/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b6e4909 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316833/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1bfe400 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d518669 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2e8ff33 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1f291d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..46118f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e432793 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316833/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316833/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316833/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316833/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316833/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316834/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c8bdd75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316834/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..02aad80 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9ae64a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..bdce920 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b3f979f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f73642f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d2795ff --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316834/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316834/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316834/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316834/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316834/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316835/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c791e60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316835/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e6572e6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4fe0445 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..276f3f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d416b8f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..80a2d4b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..8db2f5f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316835/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316835/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316835/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316835/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316835/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316836/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0348e0e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316836/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..7561cd7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..24cf21d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5ed067f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a64e530 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0be7336 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..97e407b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316836/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316836/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316836/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316836/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316836/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316837/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..614bf4f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316837/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..085815c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5117c9e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c66f419 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e4075db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e2147cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..190f387 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316837/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316837/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316837/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316837/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316837/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316838/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a88a9cf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316838/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..30f9b0c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3e7c00b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4e19302 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a56db08 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e98fca3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5bacaf9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316838/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316838/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316838/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316838/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316838/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316839/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9608304 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316839/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4ccc977 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c6cb274 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d5428e5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..029dcba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7a78bb2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..35a4e92 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316839/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316839/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316839/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316839/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316839/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316840/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..25866f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316840/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..96f8ee5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..424a319 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1ef1dac --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d46caf3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d8e6a0c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..384d21b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316840/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316840/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316840/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316840/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316840/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316841/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1958b07 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316841/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..099ff22 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..287461a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..37bc382 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c40565d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..64408df --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..77010a6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316841/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316841/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316841/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316841/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316841/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316842/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8d622f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316842/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ca22855 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..89acec8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7c09362 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d7342f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..beb35ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9410ca8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316842/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316842/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316842/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316842/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316842/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316843/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6cade0b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316843/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3e83fce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2519517 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5501f35 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..19d2350 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..96e33b5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..eb8083d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316843/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316843/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316843/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316843/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316843/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316844/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..239f6ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316844/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0c30a98 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..834df44 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..83613e5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..bc1ce67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..10574ee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1d05b04 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316844/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316844/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316844/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316844/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316844/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316845/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2303161 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316845/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..651647a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f218d08 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ba13c5e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..31883db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..badda93 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..abd23e4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316845/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316845/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316845/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316845/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316845/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316846/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2f971e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316846/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..20df71a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e5a30ea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..02dc76a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4d9a524 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..02171f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1e1dbd3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316846/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316846/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316846/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316846/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316846/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316847/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8b0f908 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316847/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..957ab20 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9a19e55 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3803920 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..dceece3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..261391e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..af74cd4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316847/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316847/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316847/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316847/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316847/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316848/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..57ca939 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316848/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..332c0f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3eca465 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..971cdd5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d3c28b8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b10a721 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0ba22fd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316848/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316848/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316848/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316848/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316848/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316849/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3bc0598 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316849/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5ecc71d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..68ec935 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b8e1d4c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f46791a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..dcd43f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ed86124 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316849/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316849/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316849/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316849/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316849/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316850/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9ee3a2c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316850/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..035421e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b9a8420 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c335414 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b8c2503 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..031d47f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2a00c5a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316850/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316850/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316850/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316850/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316850/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316851/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f1d391b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316851/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cf0949f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..560c7e6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..79fcf55 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2dc50e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e5bc970 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..698f4eb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316851/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316851/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316851/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316851/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316851/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316852/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..48d72f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316852/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..eadc614 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..84536e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f64cc9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f17bc8d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..78cf185 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fb0e636 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316852/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316852/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316852/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316852/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316852/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316853/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c1af5b8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316853/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..53433cf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e4d8354 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b18107c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3141f85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5709cc7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f50f58c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316853/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316853/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316853/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316853/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316853/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316854/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..275b907 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316854/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a9d69fa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..44c02d7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7615d54 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6c3ac2b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e26a0e5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c87132f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316854/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316854/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316854/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316854/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316854/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316855/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1079afd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316855/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f5c6be9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..40c37fd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8ca08ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a6258a4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3e7fd5a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c5b17d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316855/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316855/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316855/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316855/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316855/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316856/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ce40228 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316856/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c79a190 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f8b6a56 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2723c32 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..06cb682 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..710745b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9499c17 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316856/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316856/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316856/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316856/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316856/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316857/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..afba42b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316857/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6f31f78 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a0633aa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5a883e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..cbcde8f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cbfb813 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7fc635b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316857/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316857/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316857/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316857/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316857/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316858/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0f304f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316858/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..200c997 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d9d5722 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..529c19d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8ba4b1f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1c336a5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..02e8b9f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316858/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316858/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316858/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316858/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316858/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316859/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..44b8085 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316859/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..88ecaf2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8947f68 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..87bc000 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a63353f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4b371e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cedc01c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316859/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316859/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316859/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316859/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316859/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316860/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..321e6a5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316860/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..38ca0d0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6dade01 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..00a24c2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4ee829c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..97e465f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9f217b9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316860/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316860/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316860/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316860/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316860/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316861/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..188e656 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316861/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..975117f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4bbdded --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2d618db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e0616e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f9d8410 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7e1846c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316861/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316861/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316861/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316861/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316861/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316862/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ac93a4a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316862/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3a13bf6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5c6fdf1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d1c1f11 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..dd421c3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e790ce8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ad3236f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316862/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316862/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316862/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316862/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316862/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316863/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..242c06d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316863/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6dae56c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e5aedd9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1123dc1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6d21f95 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d0d57bd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5b148e3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316863/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316863/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316863/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316863/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316863/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316864/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fb65023 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316864/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..984c5a2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..187079c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3e22549 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..70602bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..120618f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..443600a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316864/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316864/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316864/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316864/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316864/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316865/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f273262 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316865/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1f5ba63 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9c44f51 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f169d10 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0cc612c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c18ff70 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3f8a579 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316865/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316865/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316865/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316865/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316865/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316866/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6933f5e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316866/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b4cd535 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d77fb47 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..672ac94 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7ac071d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9ea0945 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..faa8e82 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316866/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316866/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316866/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316866/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316866/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316867/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..11a88f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316867/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ddc8173 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0b85935 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d88017a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..efc47e4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..02e1cf8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e037df8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316867/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316867/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316867/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316867/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316867/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316868/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..27e58a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316868/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ac8fcf9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d8c2217 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..970be48 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4e37db7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..63e99c3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2a1ddec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316868/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316868/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316868/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316868/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316868/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316869/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..06bc401 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316869/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f138c4a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..bc006a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3c3b4be --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f237496 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4f2c101 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..01e1c0c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316869/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316869/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316869/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316869/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316869/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316870/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5e7624e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316870/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a65d7c1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e7750f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5b01eda --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ce2b3a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..595ccc7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5df253f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316870/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316870/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316870/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316870/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316870/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316871/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..25bf3ee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316871/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4c3e18e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6f7fd8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e5a15a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..73564bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d69d510 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..20e2f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316871/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316871/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316871/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316871/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316871/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316872/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0636e45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316872/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9e7ef8d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6a60550 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..332aedf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..631cc5f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e0ceeeb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2496f3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316872/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316872/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316872/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316872/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316872/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316873/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..40c6703 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316873/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..49bb598 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e220e29 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2d56465 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..445fcbe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..de8929c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1c68a77 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316873/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316873/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316873/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316873/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316873/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316874/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..be86847 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316874/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ba6f3d0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ea9596b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..240c200 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6bfcecf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..df11373 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fe3e1b7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316874/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316874/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316874/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316874/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316874/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316875/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c4110cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316875/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c8fb90b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d126d5f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c77e035 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0d710f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..19cd311 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cb0f8b4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316875/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316875/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316875/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316875/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316875/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316876/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..47673e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316876/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3381df5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e48aa54 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..78c6392 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ccf5b88 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8647cd4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..badaf39 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316876/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316876/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316876/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316876/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316876/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316877/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2e50570 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316877/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1eb33d2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..571444f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8792fed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..15d728f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ae2ea02 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cadac82 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316877/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316877/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316877/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316877/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316877/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316878/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0d460d8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316878/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3f98c2e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c52bb98 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4f76dde --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8726719 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..79951b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6c59a17 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316878/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316878/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316878/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316878/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316878/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316879/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6353b99 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316879/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..43af0f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a64bab5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2dcc8e5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d618b7f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..048ff37 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..670eff4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316879/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316879/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316879/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316879/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316879/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316880/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..98ffadf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316880/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ad2cdcd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..285786c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4a70200 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..adb6aa0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..dd831bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4445b60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316880/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316880/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316880/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316880/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316880/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316881/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b92cd80 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316881/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6e644a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8686793 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e595386 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7810cb6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..29873d9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..8fbf33e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316881/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316881/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316881/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316881/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316881/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316882/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..20d8e81 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316882/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..21e8407 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..de55f8c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3251d07 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..031161e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e6205dd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..eb45462 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316882/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316882/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316882/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316882/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316882/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316883/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..35e295a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316883/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9af3ac2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..254ec32 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a31ee0d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e60938f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a9f6af9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c2910a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316883/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316883/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316883/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316883/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316883/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316884/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..aee60d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316884/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4e48d1a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4f33243 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..dc7d04e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f805222 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b8ffd5c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d038968 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316884/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316884/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316884/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316884/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316884/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316885/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..61cb265 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316885/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9f6b981 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6449d6f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c52c539 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..dfca45b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7b38046 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f536021 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316885/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316885/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316885/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316885/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316885/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316886/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c4fcac0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316886/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3def3d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4ce38a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..dc5face --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ca6de3b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..442dbb4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..dd0721e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316886/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316886/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316886/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316886/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316886/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316887/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d319f60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316887/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a8535b3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d72dee5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a527bff --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2715135 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1db2df5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f9fe885 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316887/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316887/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316887/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316887/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316887/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316888/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..91d419b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316888/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4f24949 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4233ff9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5eeb374 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a03f870 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3700e62 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..bc5683a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316888/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316888/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316888/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316888/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316888/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316889/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..707d7dc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316889/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b9524fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7c8e4e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..be2d6ff --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3aa4760 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3ee7c64 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ca01e21 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316889/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316889/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316889/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316889/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316889/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316890/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9686df7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316890/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..83906a7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7909716 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4a7dbb3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f741081 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..13b0810 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7885ac3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316890/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316890/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316890/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316890/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316890/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316891/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..12d665c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316891/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f6644f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6e93ee9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3314f15 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d7922ec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d665c82 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cf2b613 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316891/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316891/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316891/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316891/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316891/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316892/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ae80516 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316892/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a973fe8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..67a8bfc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e3da2ed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..280be4b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5e140b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7a80e81 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316892/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316892/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316892/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316892/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316892/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316893/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8cc553c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316893/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c172207 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3385449 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4baf3d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0839d50 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..241bc08 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..06ed281 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316893/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316893/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316893/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316893/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316893/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316894/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..05f1b0d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316894/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a4ff741 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..759cdfe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e507302 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fdd7ac2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ec5cd91 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5b2a923 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316894/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316894/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316894/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316894/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316894/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316895/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4891299 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316895/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..13c8d9e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..aaebe5c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a00cf23 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3e9a711 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b28269d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ecceaf2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316895/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316895/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316895/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316895/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316895/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316896/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cffb9b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316896/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f1e7f6b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f0a7a12 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..57042a5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4e79b1c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..33d7007 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..03bd924 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316896/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316896/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316896/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316896/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316896/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316897/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..91287fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316897/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a05fee0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d884c25 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..702a179 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9a4c8c9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..35e2878 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..114ff3b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316897/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316897/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316897/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316897/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316897/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316898/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e709428 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316898/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4870a03 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ace5bde --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2974bcf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..332045f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e49a8db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ec88b19 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316898/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316898/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316898/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316898/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316898/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316899/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..924b535 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316899/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..fc60f9b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b1cec6b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b7cf85d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..80a5469 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..550f6f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f5a7be4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316899/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316899/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316899/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316899/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316899/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316900/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ab4a48b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316900/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..36084d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..18c75d8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1fc47ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6dc7004 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..676efcc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6f4492d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316900/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316900/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316900/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316900/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316900/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316901/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..61a9171 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316901/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0d1265d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8ff4f63 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..348a81a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2a346c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f40f9ac --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..63f78dc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316901/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316901/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316901/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316901/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316901/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316902/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1aad8f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316902/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3bb3698 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4b75601 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..de59eb8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7322336 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..586f91c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..49074f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316902/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316902/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316902/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316902/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316902/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316903/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e4f97e3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316903/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..008a538 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9398597 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..db2ef6c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..adb4ce2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c26cd1b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4880703 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316903/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316903/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316903/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316903/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316903/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316904/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0ee7ced --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316904/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0de39e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f6c99f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..bfe7ab7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..303c672 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e7d8df0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e251e97 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316904/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316904/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316904/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316904/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316904/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316905/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7446deb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316905/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2bf0a48 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3dc1a3a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..bd92c31 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f8147fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..974b4fb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0680092 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316905/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316905/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316905/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316905/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316905/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316906/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4787ba3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316906/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4aa7525 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..59d30e4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..30c195a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..26f5108 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..38f4739 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..26162c9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316906/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316906/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316906/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316906/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316906/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316907/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b731573 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316907/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9ae6a67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..79f2266 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6fda843 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1d1cada --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7706e15 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ba2fef3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316907/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316907/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316907/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316907/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316907/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316908/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..af66275 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316908/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..52e9350 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d01eae9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d8a55c9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..168fa68 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..79a2ac5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..843f033 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316908/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316908/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316908/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316908/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316908/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316909/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c16ea99 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316909/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b8a3058 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..977757f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c264119 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5d6c7be --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..27ae501 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..baa3da3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316909/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316909/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316909/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316909/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316909/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316910/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..35848cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316910/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b30c0e6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5a41a8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..42da98e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e5fc201 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7274a3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..eb9cb75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316910/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316910/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316910/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316910/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316910/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316911/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ac9a7f5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316911/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..696b5e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7e64239 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8c80269 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..591ecc6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3ffffb2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0017739 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316911/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316911/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316911/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316911/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316911/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316912/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a4c0bfc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316912/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d0fdf86 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e6f8f70 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d5b44bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c834a98 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9c15d87 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5ce1c08 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316912/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316912/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316912/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316912/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316912/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316913/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0e641b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316913/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2688f33 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c5b99d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..06bf572 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7f732a8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b92d8df --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..361a313 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316913/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316913/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316913/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316913/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316913/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316914/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6c51cca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316914/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..21477b6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1bab704 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..df5e629 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..45baaa6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e302200 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c5e9c1b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316914/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316914/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316914/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316914/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316914/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316915/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b384ec5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316915/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e26df5c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..10875bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..644f219 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..92a2fed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2196c52 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f170810 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316915/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316915/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316915/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316915/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316915/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316916/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d5190a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316916/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8813129 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..855ab87 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2d42b02 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..aedbb90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..da499d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..58db807 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316916/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316916/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316916/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316916/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316916/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316917/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..621ac5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316917/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..07d44f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3c3e17d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d6f33ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d377d14 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a411244 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ad250fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316917/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316917/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316917/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316917/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316917/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316918/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0bfb97c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316918/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f40ff3a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..af0c008 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..380bc28 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..06ccd88 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..18080f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..eca8a79 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316918/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316918/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316918/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316918/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316918/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316919/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4ec94f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316919/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ecee260 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..bc9ae32 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4650c11 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3304fe1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8ff8075 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ca36da6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316919/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316919/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316919/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316919/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316919/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316920/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3520bdf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316920/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..42626ca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..437b2f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f612d92 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4156ecf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..42fbc1f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0260129 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316920/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316920/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316920/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316920/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316920/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316921/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..80480fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316921/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..31e8ec8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d50d457 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9955be6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..dcaaf2b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c821ab3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..13df01f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316921/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316921/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316921/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316921/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316921/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316922/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6a13a1d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316922/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ceb9ab9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..94fab8e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2017cfd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f070218 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7a34891 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4345ffc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316922/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316922/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316922/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316922/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316922/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316923/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..12cdab3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316923/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a2bb8b4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4a9c399 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4881466 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f56a29b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..74fb603 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..8969dbb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316923/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316923/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316923/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316923/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316923/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316924/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4e98b31 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316924/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6f097a8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c98b104 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e71b085 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4a7dbbe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0cd5dcc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..013b175 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316924/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316924/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316924/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316924/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316924/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316925/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..520f0f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316925/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..41dc908 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1e68ae2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5b4eb3a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..692ed70 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e8a7504 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3a302c5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316925/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316925/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316925/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316925/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316925/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316926/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b5472ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316926/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1055eb7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0c63057 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..882c9ba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e67540d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..735ce4e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..472c4b3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316926/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316926/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316926/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316926/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316926/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316927/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..aaa7bee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316927/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8d3a9c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a5972f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4a0b52b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8fd9c33 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8b47c40 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7fd9359 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316927/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316927/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316927/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316927/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316927/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316928/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b9a959a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316928/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9b90155 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6d086f1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..09c01d7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..59cc31f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..97510c4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..337e783 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316928/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316928/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316928/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316928/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316928/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316929/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3e7f45e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316929/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..aff7c8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e1fb575 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..532488d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2bf7176 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6002e06 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d722c26 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316929/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316929/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316929/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316929/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316929/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316930/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0d6af34 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316930/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..32dc678 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..84f95d7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..231a8a5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a837e3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6bb7aa7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f766338 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316930/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316930/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316930/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316930/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316930/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316931/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..55d5bdd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316931/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6c54ab8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..bb0c98f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..100cb6d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6fc4459 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2dd61b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9b96f86 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316931/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316931/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316931/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316931/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316931/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316932/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..979c550 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316932/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..54c3eaf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4063e76 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..38dc386 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6d54572 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..55f8b3a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ce92e6a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316932/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316932/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316932/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316932/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316932/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316933/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3a73540 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316933/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2983d2f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..46a1d22 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e6c6338 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ec3c1c5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..37f7cba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1bd749c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316933/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316933/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316933/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316933/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316933/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316934/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..43ba385 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316934/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d566bcc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e6becfc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a8745f6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5a0b5f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b27032d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9833997 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316934/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316934/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316934/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316934/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316934/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316935/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5691b1d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316935/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cef69ee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..814ad34 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7b0f915 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..da4ee8c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..edc2140 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..aa84d75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316935/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316935/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316935/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316935/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316935/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316936/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..10409f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316936/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f00750b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2129611 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8cca331 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e2981a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a12773b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..56f52cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316936/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316936/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316936/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316936/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316936/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316937/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7c05405 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316937/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6dacc50 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..507176d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2c85220 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4b341f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..eff8b60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..602b68f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316937/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316937/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316937/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316937/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316937/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316938/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..83b8124 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316938/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9afb397 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ad4173a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6a8068b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..92f18e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bf9abe5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f728b3b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316938/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316938/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316938/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316938/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316938/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316939/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..57eaa1a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316939/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..44f95d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5707452 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9ecd774 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5dc04c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9b94c92 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..360ac7e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316939/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316939/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316939/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316939/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316939/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316940/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f67110a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316940/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b6a9320 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1790687 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9826b75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8f40803 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4ef7963 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..130010e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316940/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316940/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316940/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316940/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316940/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316941/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f12ef22 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316941/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ceaa66c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a4580d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d4acdb0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4e0dbbb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..48eca41 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..efd3fcf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316941/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316941/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316941/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316941/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316941/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316942/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..61ee36a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316942/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e980dcb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9097c8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9968e37 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..919115c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..100b99b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c5a16a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316942/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316942/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316942/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316942/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316942/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316943/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d39670b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316943/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ffeb74a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..db45d67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..472b70f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..152117c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a63a397 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a1a8c69 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316943/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316943/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316943/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316943/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316943/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316944/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9bf6f71 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316944/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d5081a2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..42b3dea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..df17a7c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..56eb3c4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e7f12b9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7f1ee34 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316944/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316944/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316944/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316944/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316944/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316945/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6619625 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316945/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b371621 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..bc0fff7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c0e220f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b2d5386 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3283bdc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..64eb01a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316945/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316945/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316945/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316945/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316945/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316946/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..17711d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316946/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..dfffd57 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f4f18bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8354675 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4b19745 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ebb9a2b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f98e08c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316946/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316946/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316946/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316946/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316946/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316947/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b03e167 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316947/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..06d3781 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f18a884 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9a1307d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8269cda --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..50edd75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..de5b729 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316947/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316947/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316947/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316947/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316947/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316948/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e9e68a4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316948/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8f9a079 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..20c1e11 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0207675 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5cc718a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6d1816a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a8b39bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316948/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316948/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316948/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316948/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316948/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316949/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..82700ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316949/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ab04286 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6362eba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b785feb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b2f2346 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d4fa038 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0747931 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316949/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316949/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316949/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316949/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316949/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316950/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4994b57 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316950/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a2aab02 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b7f2338 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..063acd9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..37a545e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..83cd430 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d8b7808 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316950/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316950/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316950/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316950/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316950/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316951/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..eacde2b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316951/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2f8f195 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9594914 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8d0a3d8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..cafdda7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..abd4ef0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..8e0d8be --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316951/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316951/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316951/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316951/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316951/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316952/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2f8ca51 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316952/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..7cab1e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cbab7e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..349763d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1b729bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..76ff3e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ee06db0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316952/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316952/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316952/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316952/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316952/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316953/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4a29197 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316953/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..af9e9d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0be57a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b962cbd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..cc658c3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..adbcc4f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..108cdad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316953/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316953/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316953/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316953/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316953/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316954/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..81f75f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316954/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5efd93d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5a409b7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d2dd10a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b49b308 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2435ae6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3310196 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316954/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316954/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316954/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316954/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316954/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316955/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..470a52c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316955/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8fa0d03 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f4603df --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f7f52d7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b846089 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4662660 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c90c90f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316955/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316955/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316955/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316955/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316955/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316956/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..96e80d1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316956/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..33b4541 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7ccc1af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..313ae43 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8bbfceb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b45a563 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..62f7b12 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316956/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316956/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316956/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316956/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316956/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316957/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2ec14f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316957/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c09323d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8796b66 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5a284a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0b90b63 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c36fd8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..03c0386 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316957/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316957/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316957/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316957/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316957/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316958/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cbf52b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316958/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..73c54e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ea608cc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..268a409 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e20e190 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..30e1a95 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c4e7b35 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316958/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316958/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316958/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316958/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316958/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316959/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4197c1b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316959/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..37541fa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..90ac07f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7e4d4dc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fca4238 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d87da96 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c58a04a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316959/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316959/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316959/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316959/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316959/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316960/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c6836d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316960/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..86cc7f6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d81ff19 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..119f0c4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..640ab1d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3ac06dc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f8f82e6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316960/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316960/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316960/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316960/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316960/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316961/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5a14ac9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316961/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..67b9fae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3289899 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e8bcaf0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..98dd0a2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5f2658a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..83c0fec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316961/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316961/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316961/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316961/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316961/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316962/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..511d2cc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316962/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5658a0e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b3a7f0f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1ff8c38 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..23fbf05 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..505321d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cf4ed46 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316962/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316962/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316962/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316962/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316962/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316963/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..54a4618 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316963/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d6aee79 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7b0ebfa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c3311d9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8e5b52d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..97e812e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..87ec8e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316963/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316963/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316963/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316963/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316963/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316964/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5f59150 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316964/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8d91144 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5dc7ddb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..852f370 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..93d886f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..da7962d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fde4ff8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316964/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316964/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316964/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316964/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316964/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316965/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..49a7359 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316965/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e39fe9d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8e62e90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..608e51b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f7e4d4d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..798d353 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b32d442 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316965/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316965/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316965/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316965/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316965/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316966/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6ff909d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316966/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..421607a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9a631a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d3319c8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..bb585d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..24412da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b881b1a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316966/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316966/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316966/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316966/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316966/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316967/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b25b229 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316967/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d264c85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e02cedc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..de7f59e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1858c66 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a5798c2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c276c45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316967/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316967/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316967/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316967/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316967/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316968/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..73b7c5d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316968/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..636020a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..309f296 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b049b99 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..58b7ee1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..48c89f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e8e79d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316968/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316968/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316968/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316968/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316968/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316969/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a83c902 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316969/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..13dde85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..42428cc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..02c13cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c501540 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c914741 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..76def60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316969/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316969/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316969/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316969/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316969/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316970/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3b4bf67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316970/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2ef4fcc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..148fe1a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3de451e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7c65406 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6ea2f87 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..44a8036 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316970/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316970/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316970/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316970/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316970/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316971/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6f603ce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316971/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8da1441 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..165f526 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f24f1df --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1b3aa8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1eedb52 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9ff3a50 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316971/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316971/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316971/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316971/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316971/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316972/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8b66350 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316972/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..520a27a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9db56af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f7231ac --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4c61549 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d1a7e4c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6808f9a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316972/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316972/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316972/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316972/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316972/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316973/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..38b0471 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316973/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..30e8f3e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..512f779 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1a79751 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fd7ddd0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..72a3ba5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7df2550 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316973/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316973/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316973/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316973/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316973/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316974/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b4a9ae2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316974/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bf21efc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..36ce659 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..810ca84 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a8ab4cc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f00fcc4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e6dd97e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316974/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316974/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316974/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316974/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316974/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316975/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..91d750b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316975/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c63e9b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a985c90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..41a5fa5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d9c4f3d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3f0fd2d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6374ae7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316975/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316975/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316975/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316975/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316975/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316976/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a4b1430 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316976/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e811e5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..44ffba7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..61df142 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8925869 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..de8082c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3c43e5d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316976/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316976/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316976/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316976/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316976/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316977/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bdf578f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316977/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c9d6187 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b0588bc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8c0d58d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..aee64a7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4a4f6e4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b9a8d5a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316977/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316977/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316977/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316977/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316977/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316978/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2b21cec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316978/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cdc80b8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1a550a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..cf733bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..658ac4b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cd10682 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..860f368 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316978/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316978/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316978/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316978/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316978/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316979/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a74d318 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316979/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..41e4600 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..89b3732 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4f4db65 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1606b95 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4de0ebd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c23e9bd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316979/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316979/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316979/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316979/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316979/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316980/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fe5f68c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316980/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5946d13 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f3f5a01 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..661915c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..bcfd15d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1f76d64 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c41902c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316980/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316980/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316980/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316980/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316980/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316981/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..306a8dd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316981/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c4c22ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..af39291 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a26b038 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d411509 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ba38870 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1f317f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316981/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316981/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316981/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316981/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316981/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316982/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..51eeb74 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316982/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ce3bc3e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5dfc5e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6a20e58 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2c8d6b5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d6a34e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7d744ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316982/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316982/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316982/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316982/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316982/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316983/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d65a086 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316983/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..246d1c0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f8d4225 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2384ff4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8c5c172 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4304cf8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..be82ed5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316983/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316983/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316983/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316983/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316983/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316984/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d985109 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316984/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..637f546 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cf81ff9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..cfc68cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..657f566 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..50a4b9a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..41a6e12 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316984/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316984/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316984/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316984/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316984/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316985/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..daf4e59 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316985/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..7e7ab3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..30bd39f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3bc96c1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d9c21d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..78a3cc4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6ed49c2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316985/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316985/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316985/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316985/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316985/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316986/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d53f030 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316986/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..28ba5d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..23f6bfc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8c745e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2c6ab88 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..64aff92 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..22e647a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316986/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316986/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316986/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316986/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316986/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316987/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..521bfde --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316987/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..449dfe2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ef4f396 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a6bee32 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7673ad0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1034474 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6069795 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316987/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316987/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316987/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316987/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316987/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316988/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fb8b15b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316988/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ec7fdae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..760d18b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c3ab55d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1012461 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..66d2ab0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c79cd05 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316988/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316988/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316988/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316988/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316988/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316989/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..37caa9e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316989/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3ead74a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4d57add --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..28b9ef6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c43cbe3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..805b4ec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d0b8eca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316989/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316989/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316989/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316989/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316989/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316990/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ff4cc70 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316990/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ce9a8da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c184a26 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d2ee5da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3f153b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a806238 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..479ed59 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316990/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316990/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316990/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316990/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316990/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316991/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5988833 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316991/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..fc4838d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8bec6d1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..12c324a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a2d73f5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2843683 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d10a938 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316991/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316991/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316991/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316991/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316991/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316992/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a147cc3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316992/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..52083d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..17e3edc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3abbaaa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0b69347 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..20b811f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cfdafcb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316992/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316992/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316992/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316992/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316992/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316993/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b323d8f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316993/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cbfdec6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d3c3635 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..01987a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..adde00e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8c937e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..468484b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316993/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316993/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316993/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316993/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316993/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316994/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dc36271 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316994/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0299ddd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4c090a7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0d1a83f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fb33dae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8e8a79c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..63dca95 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316994/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316994/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316994/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316994/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316994/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316995/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a6cadef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316995/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b30a4ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cd0e275 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..06f6365 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..19aac5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7887fef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a5835c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316995/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316995/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316995/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316995/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316995/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316996/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..10f1799 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316996/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..737afa7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ddc095b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1af97f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6947008 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..91f9eeb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7b1ff24 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316996/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316996/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316996/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316996/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316996/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316997/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3d0409e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316997/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..955f0aa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..131a08f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e78a19e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9be9741 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f3323fd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a1da67f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316997/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316997/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316997/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316997/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316997/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316998/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c2d322e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316998/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..7cb924f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5c065ba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..29fec67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..21cd441 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c30cebf46 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..654d68b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316998/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316998/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316998/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316998/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316998/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316999/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3d75684 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2316999/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5a68945 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7e8fb56 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4521420 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b979d02 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b83af59 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4484616 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2316999/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2316999/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2316999/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2316999/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2316999/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317000/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4aaddf1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317000/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e256f7c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b2c70bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ef01bb7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c123e39 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f784019 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e76eb62 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317000/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317000/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317000/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317000/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317000/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317001/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dabb647 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317001/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..40c0305 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c1e650c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1464d3e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..39f6f72 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4ff7238 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a4ad8b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317001/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317001/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317001/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317001/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317001/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317002/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a245ba0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317002/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e7b2392 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b31531e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..87fd8d1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1d29d7b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cdb8af6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f12aae6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317002/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317002/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317002/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317002/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317002/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317003/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..22e1982 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317003/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d1e2bac --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..518aef1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2eb54b6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c5c864c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2d664f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6b58113 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317003/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317003/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317003/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317003/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317003/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317004/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a6219b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317004/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..593ca36 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..73c5fdc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..206a755 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..053f11a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..83e074c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c155dc8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317004/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317004/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317004/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317004/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317004/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317005/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c2cd554 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317005/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b070ef0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ee8dfe4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..424ab56 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3fa75e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..74d0ce1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6465a11 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317005/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317005/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317005/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317005/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317005/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317006/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..699375e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317006/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a0caadc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0825949 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9761843 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2e55d26 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bd7ec0f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..aa13278 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317006/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317006/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317006/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317006/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317006/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317007/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7c9d074 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317007/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4147466 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c2a11f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ab9b9ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..469a757 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cbf373d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..356443c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317007/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317007/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317007/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317007/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317007/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317008/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fe4dcd4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317008/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0b8d1c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0c1e83d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..42b7c38 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6973d79 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b8d4718 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6b8d316 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317008/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317008/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317008/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317008/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317008/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317009/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5482aef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317009/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6b1de66 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7d79294 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9a4209e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f404a05 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f7f23fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..134227c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317009/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317009/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317009/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317009/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317009/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317010/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..107ae1a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317010/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3450a34 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4ab5a8c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d7ec760 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..83b2293 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c51b2c5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..809554d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317010/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317010/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317010/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317010/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317010/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317011/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a680060 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317011/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3a95863 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..607ac8f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ec03e62 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a83080b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cdfd1dc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..22cb408 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317011/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317011/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317011/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317011/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317011/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317012/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..28439cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317012/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c5f2bf3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8cf9d51 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6ba29ab --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8951551 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1fef1f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..477f6d8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317012/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317012/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317012/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317012/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317012/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317013/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..be445b8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317013/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..992d7fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1c72ebd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7c15798 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..eb0465d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f28affe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..be5bc46 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317013/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317013/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317013/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317013/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317013/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317014/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..60a357b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317014/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cb2cdb7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..26452a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..86d929f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..517fb42 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ef75a9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2a02b45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317014/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317014/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317014/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317014/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317014/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317015/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..02923ac --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317015/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..50f4543 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b615aa3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a56c58e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..032ac3e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cb18109 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..884c009 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317015/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317015/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317015/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317015/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317015/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317016/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c789bf5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317016/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9fad552 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cd1cdcc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..aea27ed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b49162a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5984c85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..da91da1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317016/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317016/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317016/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317016/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317016/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317017/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..064f04b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317017/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bbadd66 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..474bec4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d0593b3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c644e80 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..de6f591 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fd536f5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317017/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317017/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317017/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317017/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317017/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317018/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0721f6c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317018/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3778e81 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6c0c518 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..39be156 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..984e89e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..acb4f8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..eb5d974 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317018/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317018/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317018/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317018/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317018/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317019/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bcb2047 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317019/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..55f9968 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8aab7da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8970029 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4ce90d0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..18badfc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..53d5da5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317019/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317019/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317019/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317019/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317019/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317020/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a814a1e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317020/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bbf13d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..09bb497 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..626e51b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d87296e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9c94671 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3095b4e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317020/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317020/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317020/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317020/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317020/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317021/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8d80dd3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317021/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b075bc3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3cb619a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1a3f4a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..686d596 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..78db9b9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..efd8286 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317021/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317021/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317021/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317021/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317021/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317022/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1a0c53a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317022/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..56baa37 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d8cdc73 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..661b3ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f1477d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3d32e54 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..206fbd1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317022/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317022/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317022/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317022/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317022/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317023/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e047d27 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317023/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a0025f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..672f3a2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c3fd95d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d384a97 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e9ef681 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0c12128 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317023/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317023/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317023/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317023/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317023/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317024/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a4862cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317024/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cf4e72c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3cefaec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ca804e5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0586035 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f7a0f1b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..efaab3b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317024/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317024/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317024/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317024/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317024/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317025/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7882828 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317025/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c4d8904 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1a22e34 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9448f05 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1cf2e6d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9f791f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1ae528a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317025/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317025/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317025/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317025/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317025/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317026/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0fddb86 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317026/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..533e64d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..22df96b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..87ff282 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ef2d615 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..800361b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e45e9ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317026/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317026/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317026/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317026/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317026/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317027/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a4ff7ce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317027/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..abfe404 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3ae12fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b4117c6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a3664ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bbc13ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d8781ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317027/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317027/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317027/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317027/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317027/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317028/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b831de6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317028/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c21d148 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b1045a5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ddb9577 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..38c69c3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e0e07b4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b84685b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317028/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317028/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317028/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317028/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317028/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317029/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dad5f48 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317029/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ff05bc6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e05aa64 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..53efb58 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f8f0b65 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..71f2c49 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1380925 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317029/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317029/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317029/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317029/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317029/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317030/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..02b12b5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317030/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..99295fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..500ab2d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c1bea4b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..252f216 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..71f6e90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c7238d1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317030/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317030/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317030/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317030/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317030/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317031/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e6fca99 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317031/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..09ba760 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b0ad3fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1fe3bdb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3eafe41 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6de171a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..607ca94 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317031/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317031/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317031/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317031/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317031/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317032/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..529475d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317032/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..972fdb6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9abe354 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6306401 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c2571a2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e6d56b5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..81d385e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317032/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317032/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317032/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317032/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317032/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317033/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8cfb491 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317033/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bd54761 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e32512a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..92ddb14 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0f35523 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..496254f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5e7e56f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317033/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317033/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317033/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317033/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317033/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317034/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7a6cd84 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317034/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c39ee75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0c9a4da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..91ce376 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a601afa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c753a6b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a1dd329 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317034/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317034/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317034/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317034/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317034/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317035/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b324638 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317035/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..fa3766b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6430282 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d5173d2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..36935a8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..95d5a85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e5d20cf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317035/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317035/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317035/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317035/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317035/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317036/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f252f46 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317036/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3c745b9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..53fc41c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..efa215d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b49a8ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1b572a5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7a745d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317036/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317036/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317036/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317036/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317036/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317037/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a1dc069 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317037/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..62c5c2e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..78a0d5d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fc73fde --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5d2e0f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..54dada3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a47eda1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317037/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317037/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317037/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317037/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317037/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317038/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..08f7788 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317038/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4f08334 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a7587d8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f25af41 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c8470bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cf12410 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..404bca6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317038/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317038/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317038/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317038/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317038/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317039/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..36970e2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317039/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..97fe06c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1bd18a0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d04f2e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3310535 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..85e6777 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e8a7c51 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317039/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317039/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317039/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317039/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317039/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317040/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7257320 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317040/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e4d4fdc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fd01419 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..89993db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fa6c493 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..99b7dea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..df9e9a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317040/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317040/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317040/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317040/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317040/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317041/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a7e7499 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317041/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d310ac9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4b89b92 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6a94136 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..cea8567 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4ce3d8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4ac5cb0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317041/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317041/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317041/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317041/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317041/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317042/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..18f7f00 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317042/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1a4954a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ee37ab1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..62aaf3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5b1e7ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6756acf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b2ec5ce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317042/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317042/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317042/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317042/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317042/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317043/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ecc6784 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317043/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ab1d802 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c2a70cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3f768a6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..06d4d73 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c9e0026 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6996f88 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317043/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317043/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317043/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317043/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317043/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317044/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..419df2d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317044/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..27453a0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3e12002 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b4e28a2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4dd2dd2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0adf6f1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..68cdb30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317044/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317044/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317044/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317044/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317044/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317045/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a923ec0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317045/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5c0cf19 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1ca001f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7bfd6c2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5e4744c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2b8b8b6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..12be7d2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317045/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317045/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317045/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317045/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317045/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317046/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a7e9aed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317046/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5f13bfd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d9803d1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..bed5d89 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..af39380 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7e05659 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ccb12e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317046/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317046/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317046/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317046/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317046/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317047/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f95cbc3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317047/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..329b2ed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5e8a505 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c52bf64 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0f8ffd8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bfb0837 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6e8ceae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317047/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317047/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317047/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317047/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317047/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317048/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4fd63a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317048/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8dd0b9a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d74719b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9dc8b18 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..dd04a7a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6c1b493 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7a1b297 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317048/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317048/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317048/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317048/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317048/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317049/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..849e7f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317049/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4b57303 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3c65009 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3e28ef7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5e2f5d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0c3716a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..183f805 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317049/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317049/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317049/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317049/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317049/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317050/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fbf993c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317050/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d776aaa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..237fbaf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6498fba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3c1f615 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..788900e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..601feb9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317050/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317050/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317050/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317050/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317050/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317051/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..86b51af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317051/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ee52d65 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d727985 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d8086bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8b72e29 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0d3ad67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d16c918 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317051/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317051/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317051/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317051/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317051/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317052/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..29a94b4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317052/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6f570f5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7ff3937 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..29cdab9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0305557 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..06b9f0f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..898bb8c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317052/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317052/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317052/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317052/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317052/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317053/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b4fe416 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317053/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3f7e0d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..390d89e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fd89cb1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f0ff3e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bae064b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..41767f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317053/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317053/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317053/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317053/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317053/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317054/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..68301ba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317054/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2852b91 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..47badb7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3efaf3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c14abb0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..128289a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0f25330 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317054/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317054/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317054/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317054/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317054/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317055/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..358ec20 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317055/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..edf25df --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4989cd2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1c6770f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c16327c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..844f64b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..91f17f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317055/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317055/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317055/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317055/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317055/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317056/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a97321a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317056/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1665cdc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..247472e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8ba3476 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2d4619c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6e6adaa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..71a71d7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317056/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317056/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317056/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317056/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317056/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317057/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2dfc308 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317057/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..844af4d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fb545c2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..93e3050 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c806938 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a01c615 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..358651b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317057/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317057/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317057/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317057/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317057/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317058/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..588362d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317058/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0efe87e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c494c82 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..100f7b6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..eefba76 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..862a96c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6ea4fce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317058/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317058/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317058/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317058/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317058/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317059/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c86052d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317059/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3057a4c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..837d10f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..985c8ca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..82fb0fd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..28f860c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..92ae31d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317059/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317059/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317059/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317059/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317059/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317060/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0cd4643 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317060/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2962421 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2d36b03 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c0cbb37 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..069b808 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..909c0ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f5ff636 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317060/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317060/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317060/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317060/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317060/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317061/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f203db8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317061/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..811647d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2e5f8f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..47ca6ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3c684eb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1644505 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..bac9bf8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317061/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317061/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317061/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317061/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317061/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317062/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fb6ac46 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317062/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..68aa24d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4115ee8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..dc88c3d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7b8dd05 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..db1ff35 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e3c7731 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317062/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317062/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317062/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317062/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317062/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317063/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9f39e61 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317063/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2ee360c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5aeba08 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8124fe4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..84ac6a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..63ca52c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..8edd7f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317063/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317063/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317063/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317063/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317063/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317064/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..989d841 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317064/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a41b6e6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9022eb3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..aa59317 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1978fa6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ab9cf3c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..eef240a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317064/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317064/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317064/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317064/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317064/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317065/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..633d4c3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317065/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d8cd544 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9f36498 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..be214bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..58747f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7fd6eb5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b7c2fdc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317065/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317065/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317065/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317065/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317065/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317066/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e605ff9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317066/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ccbbd03 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e4d5a84 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..620e092 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d46b9d8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..85a92fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0ab81e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317066/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317066/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317066/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317066/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317066/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317067/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c1a94a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317067/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8b62128 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4fd08f6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..10cda19 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6bc93f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c994f1c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..59a1955 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317067/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317067/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317067/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317067/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317067/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317068/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bf2909b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317068/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ebd2dc1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..315a3a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..04245d7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9ea64d7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0a6bc13 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fff90e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317068/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317068/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317068/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317068/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317068/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317069/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..79f109b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317069/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..40d9e28 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..11c755f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d6eee63 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9125f1a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e987652 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..aa9b9f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317069/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317069/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317069/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317069/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317069/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317070/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ab08eb2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317070/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2898abe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ee076c8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5409e1f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..562d9ac --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8872538 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3655704 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317070/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317070/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317070/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317070/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317070/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317071/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dfc7aca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317071/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3a47932 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f3e0063 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0d83bae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..956c0b9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..58edb8d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..be594d0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317071/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317071/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317071/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317071/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317071/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317072/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e94e530 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317072/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..aa24923 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fb1b1bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5b581a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..322e026 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0f1d387 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e595f6c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317072/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317072/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317072/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317072/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317072/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317073/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..69985de --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317073/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0df8a8e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2a20ba9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..cb8b3ba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..da30c9f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..13a82f1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..43e9101 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317073/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317073/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317073/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317073/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317073/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317074/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2ecc848 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317074/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..345056d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fb4c4d0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8a19650 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d83bde3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ac64ac2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..213c73f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317074/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317074/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317074/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317074/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317074/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317075/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bdf7126 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317075/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..92c1d83 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6357623 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c5b13ab --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0ab91a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..dd4266a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7d2d199 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317075/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317075/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317075/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317075/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317075/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317076/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..52e709e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317076/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a9c06f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..68ae251 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..02c0ccc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b5fa3d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f1036fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ac028e6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317076/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317076/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317076/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317076/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317076/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317077/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ced3096 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317077/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1ba5c5a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d0096be --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c7d950e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3b7bfdb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d12484f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9c1c4b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317077/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317077/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317077/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317077/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317077/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317078/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..40d0d96 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317078/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a084e6b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f39fbab --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..43d3281 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a001448 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..01cce9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a9177fe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317078/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317078/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317078/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317078/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317078/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317079/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d5e5fe0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317079/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..77d2b65 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f362b5d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..543fc5f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..308633c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..32ba6e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b30f8f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317079/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317079/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317079/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317079/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317079/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317080/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2eaf7af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317080/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..44f7c08 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..84233d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2df72f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..36f0517 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d5f9c8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cbbbd2d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317080/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317080/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317080/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317080/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317080/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317081/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..04f2ded --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317081/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..32186e5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e62b15c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3e87934 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b5612ea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1136984 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b038832 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317081/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317081/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317081/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317081/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317081/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317258/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..71cf39d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317258/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ce89853 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..dff6bfb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ed04b06 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..746e6ae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..141af07 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..28e4cff --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317258/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317258/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317258/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317258/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317258/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317259/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0a99923 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317259/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..fd2fe42 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..58db910 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fac26aa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a9f9afc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..252c139 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..bc5bdd1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317259/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317259/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317259/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317259/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317259/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317260/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6ee4719 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317260/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..92a7c1b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ce4a251 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..417df7b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4ec2b4e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1de34b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..dc13657 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317260/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317260/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317260/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317260/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317260/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317261/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e85f0d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317261/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c391af3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..db18787 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d445e67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..24ee504 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9ff03da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0547187 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317261/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317261/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317261/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317261/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317261/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317262/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..036ddea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317262/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..932e6b4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..362c323 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..959d844 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e78c442 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c6184ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9dad258 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317262/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317262/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317262/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317262/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317262/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317263/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6bf09c2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317263/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bbf969b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9157d99 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2ecea6a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7a76831 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a8b9cee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0aeb56c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317263/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317263/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317263/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317263/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317263/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317264/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d7d009d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317264/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ef87e51 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5131df4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7324b30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..43f4f7f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bf9dc4f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d7bd44f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317264/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317264/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317264/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317264/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317264/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317265/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c3fedbe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317265/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1a722a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0371b33 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a00947c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f557197 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..65c1563 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1b4ca2a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317265/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317265/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317265/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317265/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317265/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317266/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1d8022b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317266/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..248da42 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cc65969 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..61907ed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3b73f77 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..41402de --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..66833bc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317266/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317266/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317266/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317266/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317266/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317267/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f115488 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317267/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6b4e48f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..61d9ed9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f63ddb8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3b41ff3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d9488fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a5ab77b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317267/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317267/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317267/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317267/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317267/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317268/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..537e097 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317268/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..520496c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..87b108d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6e8534a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4e71fcd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4efdc3d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..745146c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317268/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317268/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317268/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317268/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317268/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317269/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4fb18bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317269/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c164421 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b2961b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0f0159b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..23645f9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7a71486 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ed855db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317269/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317269/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317269/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317269/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317269/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317270/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9f989d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317270/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..19815c1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2462964 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..49bad49 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b546a11 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7163e5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7be4b90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317270/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317270/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317270/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317270/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317270/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317271/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..915d1c8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317271/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1e83d2d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..06fb0af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7fa445a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..eff9095 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6820744 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e73e907 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317271/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317271/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317271/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317271/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317271/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317272/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..869b9d8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317272/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2883dfc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..24fdc53 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b39e255 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b186c59 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ed2ff16 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..132ec9b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317272/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317272/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317272/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317272/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317272/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317273/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1749f90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317273/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e31482c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..54fc38a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..085ae2a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2d86a74 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2e3667d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c1d2669 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317273/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317273/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317273/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317273/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317273/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317274/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..56e30af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317274/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1272114 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d18fad0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..faebd95 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..eb9010c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cf16ef1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0ec0e8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317274/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317274/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317274/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317274/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317274/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317275/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6535610 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317275/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e5b1ca4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4023f40 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..bf95a8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..de46872 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9569575 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..da8ebe5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317275/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317275/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317275/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317275/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317275/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317276/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0fe4ebb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317276/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d5dc06d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..dd7feec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..857aa78 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7470f5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..40ecbbc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c2350b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317276/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317276/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317276/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317276/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317276/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317277/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..17c43bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317277/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..971b6d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..dbfd8ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..28208f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..75554a7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..097a2fd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2c1c1a9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317277/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317277/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317277/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317277/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317277/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317278/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2dc1929 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317278/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..be26ec0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ca301da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..92eecc1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4d80fe9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4cc2a45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e713e4f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317278/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317278/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317278/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317278/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317278/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317279/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cb4b2aa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317279/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..47ecc91 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d00d87e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a6e741b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..0dc8fcc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c657328 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6e7f0d9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317279/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317279/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317279/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317279/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317279/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317280/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8d4e7e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317280/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f1d3968 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2c6eb1d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..aeb7055 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..dac9227 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..621d171 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..605fda1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317280/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317280/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317280/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317280/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317280/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317281/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c30aa82 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317281/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..00e6ddb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fd57eb3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8532b10 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6ecfe54 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..53114fa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1e4eb2b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317281/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317281/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317281/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317281/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317281/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317282/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c843e29 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317282/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3812d85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fb16fd1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4866532 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c8c8b46 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a1043a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9b25472 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317282/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317282/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317282/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317282/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317282/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317283/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1d935e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317283/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..08a6bad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..18f9cbb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..061a8c0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9f01c50 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..02a6329 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e2c9ae1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317283/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317283/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317283/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317283/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317283/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317284/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5eaeb71 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317284/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cefffd3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5f72156 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8534f60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5c19754 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..046fad5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..32e452e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317284/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317284/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317284/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317284/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317284/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317285/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2e9fd88 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317285/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b088978 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ead0563 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1c252a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..eb266b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..485aabf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9aa0319 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317285/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317285/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317285/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317285/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317285/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317286/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3747203 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317286/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e604fce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..652818f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1fe50e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8462423 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..730b7be --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cb51734 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317286/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317286/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317286/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317286/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317286/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317287/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9191e76 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317287/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..53ec468 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6c301db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9e4eb1b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f52e168 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..113381e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..64d6b50 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317287/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317287/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317287/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317287/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317287/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317288/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6aeac09 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317288/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..efb7fda --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e171aee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3ea30db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fd0eadc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8714f75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..36327ed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317288/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317288/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317288/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317288/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317288/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317289/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..722238b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317289/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5cb1755 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f1dfb20 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..aeac260 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..47d429f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..012a448 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7504ef7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317289/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317289/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317289/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317289/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317289/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317290/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..51c80e3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317290/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b1a3e16 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e9db9f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c101b09 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fd62aad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e8966c6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6c07816 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317290/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317290/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317290/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317290/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317290/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317291/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..25b127f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317291/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..99df54f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..347de57 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..bc936a6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1fd2715 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f04f1f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..81079e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317291/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317291/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317291/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317291/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317291/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317292/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..15cd8c3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317292/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2bf53f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f1183fb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..df4ad8e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..18ddb85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3cbff30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3e207f3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317292/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317292/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317292/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317292/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317292/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317293/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..961e8ce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317293/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f93551c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..84a51b5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..644cd2b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6b1d961 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0c4974c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b8e3f0b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317293/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317293/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317293/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317293/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317293/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317294/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5859dd3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317294/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bf5ae4f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..af84f1d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..da1f278 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a7b26ef --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..38ab393 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3df74cc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317294/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317294/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317294/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317294/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317294/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317295/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8f23141 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317295/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d878bba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ae8fdec --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ad54ff6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8dc1320 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f7851a8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..eb52419 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317295/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317295/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317295/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317295/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317295/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317296/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9554e71 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317296/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2b4bfc8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d1c3866 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b905881 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7e62c79 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0db835c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a2010e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317296/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317296/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317296/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317296/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317296/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317297/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7fad9fb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317297/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..7b4b050 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cccc73f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..dbfe74c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e081882 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..f67d96d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1de68d4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317297/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317297/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317297/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317297/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317297/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317298/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..36c5ca4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317298/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..0ac38cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ba0312d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3966c7f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..fffedf4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ece08b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..df6c8ca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317298/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317298/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317298/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317298/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317298/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317299/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d24d379 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317299/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ddb61cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..de0f16d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9faa968 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..99cd4b5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..cd08d8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4484bb1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317299/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317299/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317299/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317299/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317299/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317300/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..568d363 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317300/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f2121f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fe7aae3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0cb73de --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6787e3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..fa9f3e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..db8c280 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317300/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317300/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317300/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317300/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317300/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317301/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..038b0ee --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317301/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..15ab502 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4db7619 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0bbeae5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..49bdc04 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3699558 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6d4746e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317301/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317301/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317301/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317301/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317301/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317302/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..eabfbd6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317302/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..73c0af9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4eb8e5b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ae35656 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ad7157c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6803023 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..30d1d95 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317302/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317302/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317302/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317302/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317302/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317303/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..aaa6d4f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317303/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..748b853 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c89d206 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1c0dc3b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d294d1d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..b98fdd3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3faa426 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317303/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317303/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317303/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317303/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317303/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317304/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8e513de --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317304/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4303c34 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c03e2e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6c30be3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d1814d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1ea3540 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..74685e2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317304/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317304/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317304/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317304/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317304/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317305/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2d2a1bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317305/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..bbdaa1c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3a6e9bd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5d798b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..bf2d2c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e59e43b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..becb13d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317305/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317305/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317305/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317305/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317305/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317306/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ba8693e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317306/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..95e4c4a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..32eb41d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a5e80d5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d0a05f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2087507 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b3c2c66 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317306/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317306/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317306/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317306/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317306/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317307/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fa1adcf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317307/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..001f7cc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cd3b357 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8954714 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9c2acea --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d75ddc6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c553ad9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317307/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317307/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317307/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317307/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317307/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317308/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5e21add --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317308/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3e39354 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6a32e28 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7d5f65e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..dfc8a12 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d62fad2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..512d43f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317308/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317308/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317308/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317308/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317308/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317309/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..02132e3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317309/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3dca3e3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1d8f138 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..494caa7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2c03c11 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ee48b84 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..809fda5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317309/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317309/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317309/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317309/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317309/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317310/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7b97547 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317310/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b8081bd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1f54049 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ea572fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..14b93a4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..14caa6f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..83882d2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317310/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317310/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317310/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317310/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317310/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317311/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..88bd358 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317311/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a918ea1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0033186 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8d70dd1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8dba978 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d395e8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5b47858 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317311/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317311/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317311/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317311/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317311/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317312/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0778726 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317312/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..219b3b6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d5e760e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0748031 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..afe5ab4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4c58845 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6926b4b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317312/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317312/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317312/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317312/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317312/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317313/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dd8d474 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317313/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6994508 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ed13fad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ea44d13 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9a05a0e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..26cd70b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..467a351 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317313/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317313/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317313/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317313/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317313/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317314/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dbd4a17 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317314/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3e3baca --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fe95142 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..14a8a78 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..6cca759 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a0eeef8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1e70118 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317314/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317314/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317314/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317314/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317314/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317315/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ba0988d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317315/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d3ecdc1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4d27c7c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..eafbafa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..aff81a7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..854cb1b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6a6f583 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317315/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317315/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317315/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317315/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317315/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317316/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..95b2a2a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317316/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5f73f7a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9cd0fa3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c42924f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5826294 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..35b0357 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cfd635a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317316/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317316/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317316/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317316/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317316/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317317/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6959e29 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317317/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..90b5928 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e59ff70 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8fde0ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..08920c8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..017d31e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..56aa5da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317317/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317317/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317317/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317317/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317317/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317318/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7657b71 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317318/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1e2c138 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..97ec6b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fb40d53 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ab346e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d992602 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a41caf3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317318/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317318/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317318/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317318/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317318/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317319/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e6679c9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317319/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6b89f79 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..88d75c4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0ca2705 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ac37195 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a21dadb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..de8ba0f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317319/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317319/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317319/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317319/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317319/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317320/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0adb005 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317320/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..10864d3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fe5090c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..43fdfc8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..15bc0c5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..70db188 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a54265e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317320/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317320/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317320/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317320/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317320/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317321/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c4d6738 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317321/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..89a3fc8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..bdd4205 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..37baf45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..743ecf2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9a7204f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1d2e7f4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317321/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317321/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317321/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317321/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317321/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317322/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..52aae4e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317322/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..29d5926 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8a36a37 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..823304f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..746997e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..738fa28 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5db6daf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317322/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317322/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317322/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317322/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317322/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317323/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1ba0cb4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317323/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a8312a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2f4ead3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2839b45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f2cf166 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c3c7280 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3ab61b1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317323/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317323/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317323/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317323/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317323/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317324/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c42eba5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317324/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..376de0b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..e2f2193 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2c168f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9a84a53 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..e8972aa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..9078e0c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317324/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317324/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317324/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317324/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317324/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317325/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a42addd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317325/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..53403b6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ba99d8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..25c63bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..694c034 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..7a2a6cd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f930db7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317325/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317325/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317325/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317325/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317325/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317326/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..88f29aa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317326/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a1af977 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..3869640 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..766c290 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ef095f6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5611ac2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..00e62b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317326/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317326/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317326/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317326/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317326/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317327/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b2680e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317327/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ddb3a80 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d884410 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..3ab3711 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3fdffa9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..52c44cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6b1f0fa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317327/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317327/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317327/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317327/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317327/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317328/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1ebe620 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317328/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a31222f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..d30eb04 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ddd2789 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..af93257 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4cfa10b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ee4857d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317328/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317328/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317328/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317328/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317328/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317329/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..be59a14 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317329/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..120c74f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..9c558c6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f4e2935 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..accc45c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..6bc9baa --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..cbf126f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317329/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317329/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317329/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317329/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317329/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317330/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..16e4b6e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317330/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ba4e9e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..c8535b8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..51a6cf2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2f81b5d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d879c11 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..773273c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317330/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317330/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317330/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317330/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317330/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317331/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..742cd57 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317331/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..8fcfe38 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ab3708e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9314e53 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2c07602 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..8bf6473 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5c7c1eb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317331/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317331/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317331/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317331/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317331/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317332/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2a72263 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317332/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..452f6c6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6eb173c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2100699 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a5c1193 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..dd80e10 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b2cf4a4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317332/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317332/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317332/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317332/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317332/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317333/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b73e790 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317333/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d9d15e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1785dab --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..613ecbc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..aac712f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2a62775 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..b726c6f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317333/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317333/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317333/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317333/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317333/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317334/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..db6a215 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317334/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..82a4d04 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..49a0270 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..505134e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..7e1caad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c6d937f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..5b7f91b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317334/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317334/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317334/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317334/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317334/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317335/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1d46a63 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317335/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5e68b67 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1fbae53 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5f9faa0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e3e3bf5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..aa9a6b4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ce6b0ac --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317335/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317335/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317335/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317335/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317335/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317336/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fcdeb62 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317336/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2bdbee6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f7b55d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fb1e9a3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..4da9d60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a48b98a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..71ddfdd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317336/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317336/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317336/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317336/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317336/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317337/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d1d7b47 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317337/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..5039244 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..35bb823 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..55a618e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9280d14 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..485bfbf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..6cf55e2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317337/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317337/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317337/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317337/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317337/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317338/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6586f9a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317338/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b0e63a5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a4f2b76 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..17fde90 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..55238b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..31d8cae --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3e9a2e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317338/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317338/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317338/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317338/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317338/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317339/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2874910 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317339/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..654e3b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..038fcfd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ae09101 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..77a3c1e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c4717a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3ea40be --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317339/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317339/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317339/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317339/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317339/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317340/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..64346d9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317340/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..27bb9b2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ea8948e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..f3af05f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..152143e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..934763d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4034b32 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317340/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317340/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317340/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317340/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317340/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317341/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3ec8692 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317341/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a70ec78 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..35bc121 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..541f456 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c8f14f1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1343529 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..4599a02 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317341/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317341/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317341/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317341/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317341/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317342/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..39f9fba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317342/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f7d6d65 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..24338bd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7362714 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..e719bb1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9c88289 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..84f2615 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317342/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317342/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317342/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317342/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317342/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317343/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3be352a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317343/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e1045ce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..5fc4a9a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..de22730 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f4c049f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..87bd485 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..32fa2af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317343/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317343/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317343/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317343/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317343/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317344/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..75c6487 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317344/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..988812a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f3851cc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..cbcd821 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..1418737 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..80a6a86 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d268770 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317344/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317344/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317344/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317344/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317344/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317345/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a316374 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317345/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..75a0c00 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..28a022e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e97b8c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..68d700c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d64f1e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f371f26 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317345/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317345/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317345/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317345/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317345/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317346/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d242e50 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317346/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..6831fe9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..eb45b3a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..31afcf2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3e2f0f6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5cd4cdb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..044233d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317346/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317346/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317346/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317346/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317346/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317347/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bc4cf6c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317347/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..aa8e864 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f1ba465 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..5c07833 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..75f402e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0b893df --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..bf37637 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317347/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317347/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317347/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317347/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317347/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317348/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..af423c7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317348/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1293652 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f607839 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c53670c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..5f4324c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3b7da06 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a866a05 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317348/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317348/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317348/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317348/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317348/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317349/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..218a678 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317349/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2176203 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b3005af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..2266b85 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..783be57 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..30407cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..e3aa62a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317349/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317349/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317349/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317349/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317349/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317350/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a1bbbfc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317350/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..07270c1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7d02a56 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..0447338 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2309468 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..263b937 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0e16f56 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317350/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317350/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317350/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317350/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317350/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317351/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8b9fbb1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317351/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b6f2d91 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cdc448d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..12a2836 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..786321b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..2fee74e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..0841f13 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317351/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317351/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317351/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317351/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317351/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317352/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f0bcc9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317352/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e43f3db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8b0df48 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..27448bd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..ccf88da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..1bbe77b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fbc563c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317352/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317352/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317352/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317352/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317352/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317353/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e7ed7c3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317353/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..23e1249 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..8be730b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..9db4f45 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b9a9899 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c17f97d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7a60982 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317353/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317353/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317353/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317353/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317353/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317354/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..33855a2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317354/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..cb9cdbb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..b9eb51a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..d8a4d04 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9165573 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9a63ae9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d77f704 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317354/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317354/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317354/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317354/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317354/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317355/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..43664fc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317355/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..9ea29b8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..554c8e2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fc5a436 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..adf8c9d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..140f3b8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a5c386d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317355/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317355/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317355/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317355/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317355/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317356/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..281aa0a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317356/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..1b9ea4e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..36cf4eb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..cfc3095 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..a3f92dd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0e7e937 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d1566db --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317356/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317356/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317356/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317356/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317356/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317357/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..88c1eed --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317357/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4091131 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..a881bcf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..a28d5dd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2025dce --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bf57101 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fc41cbc --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317357/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317357/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317357/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317357/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317357/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317358/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cad81e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317358/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d90d76f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ef42e37 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..881246f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..8b223f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..df19ef5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f097527 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317358/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317358/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317358/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317358/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317358/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317359/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..29a40b4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317359/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..89cd25a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..fdc537f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..e497647 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d4e54af --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..dbac9a7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f79dea8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317359/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317359/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317359/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317359/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317359/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317360/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..29d576c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317360/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..61e982b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cf7f02d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..edae0a0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d98b798 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..807f200 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..d1b91a0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317360/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317360/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317360/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317360/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317360/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317361/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6e5ed9e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317361/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3c235e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..ddb3da6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7301eba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b291bc2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..d4661d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..ea0d53d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317361/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317361/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317361/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317361/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317361/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317362/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0916fd7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317362/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..840c6f0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..344bdc7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..4487e15 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..b687b26 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..bcd21bf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2c2fbfd --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317362/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317362/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317362/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317362/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317362/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317363/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..829a5a1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317363/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d20b7b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..2122a2e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..7a8f946 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2abb9a0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..00b4d8a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..29e7889 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317363/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317363/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317363/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317363/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317363/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317364/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1f285bb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317364/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e048510 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..efbb76a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6fd7086 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..da956e8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9d91548 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c22a408 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317364/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317364/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317364/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317364/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317364/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317365/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..138e8e7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317365/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a0a01cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..952f9da --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..99e9da2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..2fe1833 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ede3ad1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f8ea36a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317365/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317365/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317365/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317365/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317365/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317366/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2dab27e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317366/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..d1fcd60 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cee270d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..950e51b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..3b328e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c18dbd5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..de47162 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317366/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317366/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317366/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317366/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317366/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317367/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ff3f484 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317367/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b1a8a0f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..484ee3c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..015cf8b --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..9c1e8e1 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..0114839 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2f2b5f8 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317367/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317367/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317367/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317367/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317367/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317368/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..be24327 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317368/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..ab6800d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..cf88f75 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..afa72cb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..abd035a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..a4c6ae5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..dce176c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317368/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317368/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317368/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317368/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317368/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317369/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a9a46f2 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317369/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..2631657 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..430c88e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..b45e69d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..d212d06 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4bab626 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..a72ccdf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317369/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317369/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317369/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317369/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317369/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317370/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..796152d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317370/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..20f8416 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..894c9b7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..bbdeca4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..781f76a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..85de373 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..fb708ad --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317370/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317370/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317370/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317370/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317370/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317371/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..550cb0a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317371/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..b0bde3f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f3a3505 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..c51b9e9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..64ef5c5 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..c6a4916 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c65dc5f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317371/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317371/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317371/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317371/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317371/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317372/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c56380e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317372/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..a70b259 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..1edd517 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..8b8c82d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..af9fa71 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..5f1567f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3e16ae3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317372/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317372/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317372/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317372/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317372/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317373/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b5d7116 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317373/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..e3faf6d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..778fcd9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..fe98be3 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..c307161 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9be4887 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..3e04dde --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317373/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317373/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317373/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317373/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317373/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317374/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a62c4e0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317374/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..3fcb22f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..4786da4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..ab2a7ba --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..070e33a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..9c028f7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..f8c1857 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317374/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317374/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317374/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317374/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317374/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317375/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..56c3849 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317375/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..f6451b0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..0feed70 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..29c464e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..75757fb --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..3d6d385 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..2b58085 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317375/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317375/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317375/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317375/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317375/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317376/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f61c1d6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317376/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4a1bd9d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..95a0f99 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..1fbdcd6 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..02233d9 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..aee0e2a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1956713 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317376/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317376/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317376/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317376/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317376/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317377/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2ef5026 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317377/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..4930d7a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..6c1fdaf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..353309d --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..47dba63 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..163490e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..1dc4640 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317377/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317377/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317377/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317377/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317377/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317380/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ed4d847 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317380/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..290bc8e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..f783715 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..6b1feb4 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..f17c846 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..ea36e2a --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..c0a6561 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317380/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317380/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317380/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317380/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317380/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317385/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4dabeb7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/__pycache__/pdg_const1.cpython-37.pyc b/data/CLs/finished/f1d1/-+/D-True/2317385/__pycache__/pdg_const1.cpython-37.pyc new file mode 100644 index 0000000..c225656 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/__pycache__/pdg_const1.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s--CLs_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s--CLs_list.pkl new file mode 100644 index 0000000..7b1359f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl new file mode 100644 index 0000000..99cbbdf --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl new file mode 100644 index 0000000..86d6e7e --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--Ctt_error_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl new file mode 100644 index 0000000..4a44fbe --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--Ctt_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl new file mode 100644 index 0000000..7d1c5a7 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/0.0001-0.003_20s1b1t--pull_dic.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/variab.pkl b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/variab.pkl new file mode 100644 index 0000000..bb90dc0 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/data/CLs/variab.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/helperfunctions.py b/data/CLs/finished/f1d1/-+/D-True/2317385/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/pdg_const1.py b/data/CLs/finished/f1d1/-+/D-True/2317385/pdg_const1.py new file mode 100644 index 0000000..70b3f30 --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/pdg_const1.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + # + # "rho": (743.2, 149.0, -0.22, 1.05), + # + # "omega": (782.7, 8.5, 0.38, 6.8), + # + # "phi": (1013.5, 4.25, 0.62, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.63, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, 1.8, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.95, 2.5), + # + # "p4040": (4039.0, 80.0, -2.75, 1.01), + # + # "p4160": (4191.0, 70.0, -2.28, 2.2), + # + # "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/-+/D-True/2317385/raremodel-nb.py b/data/CLs/finished/f1d1/-+/D-True/2317385/raremodel-nb.py new file mode 100644 index 0000000..c326c9c --- /dev/null +++ b/data/CLs/finished/f1d1/-+/D-True/2317385/raremodel-nb.py @@ -0,0 +1,2152 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[ ]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" +import random +import numpy as np +from pdg_const1 import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[ ]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[ ]: + + +def formfactor(q2, subscript, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): #returns real value + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2. * (mB**2. * mK**2. + mK**2. * q2 + mB**2. * q2) / mB**2.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + bracket_left = 2./3. * tf.pow(kabs,2) * tf.pow(beta,2) * tf.pow(tf.abs(ztf.to_complex(C10eff)*formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + bracket_middle = _top/_under *tf.pow(tf.abs(ztf.to_complex(C10eff) * formfactor(q2, "0", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)), 2) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + kabs = ztf.sqrt(mB**2. + tf.pow(q2, 2)/mB**2. + mK**4./mB**2. - 2 * (mB**2 * mK**2 + mK**2 * q2 + mB**2 * q2) / mB**2) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + abs_bracket = tf.pow(tf.abs(c9eff(q, funcs) * formfactor(q2, "+", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + ztf.to_complex(2.0 * C7eff * (mb + ms)/(mB + mK)) * formfactor(q2, "T", b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2)),2) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[ ]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + return ztf.to_complex(2) - G(ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) + +def h_P(m, q): + + return ztf.to_complex(2/3) + (ztf.to_complex(1) - ztf.to_complex(4*tf.pow(m, 2)) / ztf.to_complex(tf.pow(q, 2))) * h_S(m,q) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[ ]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + Dbar_contrib = ztf.to_complex(self.params['Dbar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['Dbar_phase']))*ztf.to_complex(h_S(self.params['Dbar_mass'], q)) + DDstar_contrib = ztf.to_complex(self.params['DDstar_scale'])*tf.exp(tf.complex(ztf.constant(0.0), self.params['DDstar_phase']))*(ztf.to_complex(h_P(self.params['Dstar_mass'], q)) + ztf.to_complex(h_P(self.params['D_mass'], q))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + return ztf.to_complex(self.params['C_tt'])*(ztf.to_complex((h_S(self.params['tau_mass'], q))) - ztf.to_complex(h_P(self.params['tau_mass'], q))) + + + funcs = rho_res(x) + omega_res(x) + phi_res(x) + jpsi_res(x) + psi2s_res(x) + p3770_res(x) + p4040_res(x)+ p4160_res(x) + p4415_res(x) + P2_D(x) + ttau_cusp(x) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[ ]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +rho_s = zfit.Parameter("rho_s", ztf.constant(rho_scale), lower_limit=rho_scale-np.sqrt(rho_scale), upper_limit=rho_scale+np.sqrt(rho_scale)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +omega_s = zfit.Parameter("omega_s", ztf.constant(omega_scale), lower_limit=omega_scale-np.sqrt(omega_scale), upper_limit=omega_scale+np.sqrt(omega_scale)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +phi_s = zfit.Parameter("phi_s", ztf.constant(phi_scale), lower_limit=phi_scale-np.sqrt(phi_scale), upper_limit=phi_scale+np.sqrt(phi_scale)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +jpsi_s = zfit.Parameter("jpsi_s", ztf.constant(jpsi_scale), floating = False) #, lower_limit=jpsi_scale-np.sqrt(jpsi_scale), upper_limit=jpsi_scale+np.sqrt(jpsi_scale)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +psi2s_s = zfit.Parameter("psi2s_s", ztf.constant(psi2s_scale), floating = False) #, lower_limit=psi2s_scale-np.sqrt(psi2s_scale), upper_limit=psi2s_scale+np.sqrt(psi2s_scale)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p3770_s = zfit.Parameter("p3770_s", ztf.constant(p3770_scale), lower_limit=p3770_scale-np.sqrt(p3770_scale), upper_limit=p3770_scale+np.sqrt(p3770_scale)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4040_s = zfit.Parameter("p4040_s", ztf.constant(p4040_scale), lower_limit=p4040_scale-np.sqrt(p4040_scale), upper_limit=p4040_scale+np.sqrt(p4040_scale)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4160_s = zfit.Parameter("p4160_s", ztf.constant(p4160_scale), lower_limit=p4160_scale-np.sqrt(p4160_scale), upper_limit=p4160_scale+np.sqrt(p4160_scale)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +p4415_s = zfit.Parameter("p4415_s", ztf.constant(p4415_scale), lower_limit=p4415_scale-np.sqrt(p4415_scale), upper_limit=p4415_scale+np.sqrt(p4415_scale)) + + +# ## Dynamic generation of 2 particle contribution + +# In[ ]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[ ]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-2.5, upper_limit=2.5) + + +# ## Load data + +# In[ ]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# with open(r"./data/slim_points/slim_points_toy_0_range({0}-{1}).pkl".format(int(x_min), int(x_max)), "rb") as input_file: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[ ]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +total_f_fit = total_pdf_full(obs=obs_fit, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[ ]: + + +# total_f_fit.normalization(obs_fit) + + +# ## Test if graphs actually work and compute values + +# In[ ]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + + + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) + +Ctt.set_value(0.5) + +calcs_test1 = zfit.run(probs) + +Ctt.set_value(0.0) + +Dbar_s.set_value(0.3) + +DDstar_s.set_value(0.3) + +calcs_test2 = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[ ]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)') +plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)') +plt.plot(test_q, calcs_test2, label = 'pdf (D-contribs = 0.3)') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[ ]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[ ]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[ ]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[ ]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[ ]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[ ]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[ ]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[ ]: + + +# zfit.settings.set_verbosity(10) + + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[ ]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[ ]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[ ]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[ ]: + + +# jpsi_width + + +# In[ ]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[ ]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[ ]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[ ]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[ ]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[ ]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[ ]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[ ]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[ ]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[ ]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +sum_list.append(ztf.to_complex(jpsi_s) * tf.exp(tf.complex(ztf.constant(0.0), jpsi_p)) * ztf.to_complex(jpsi_w / (tf.pow(jpsi_m,3)))) +sum_list.append(ztf.to_complex(psi2s_s) * tf.exp(tf.complex(ztf.constant(0.0), psi2s_p)) * ztf.to_complex(psi2s_w / (tf.pow(psi2s_m,3)))) +sum_list.append(ztf.to_complex(p3770_s) * tf.exp(tf.complex(ztf.constant(0.0), p3770_p)) * ztf.to_complex(p3770_w / (tf.pow(p3770_m,3)))) +sum_list.append(ztf.to_complex(p4040_s) * tf.exp(tf.complex(ztf.constant(0.0), p4040_p)) * ztf.to_complex(p4040_w / (tf.pow(p4040_m,3)))) +sum_list.append(ztf.to_complex(p4160_s) * tf.exp(tf.complex(ztf.constant(0.0), p4160_p)) * ztf.to_complex(p4160_w / (tf.pow(p4160_m,3)))) +sum_list.append(ztf.to_complex(p4415_s) * tf.exp(tf.complex(ztf.constant(0.0), p4415_p)) * ztf.to_complex(p4415_w / (tf.pow(p4415_m,3)))) +sum_list.append(ztf.to_complex(DDstar_s) * tf.exp(tf.complex(ztf.constant(0.0), DDstar_p)) * (ztf.to_complex(1.0 / (10.0*tf.pow(Dstar_m,2)) + 1.0 / (10.0*tf.pow(D_m,2))))) +sum_list.append(ztf.to_complex(Dbar_s) * tf.exp(tf.complex(ztf.constant(0.0), Dbar_p)) * ztf.to_complex(1.0 / (6.0*tf.pow(Dbar_m,2)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +Cov_matrix = [[ztf.constant( 1.), ztf.constant( 0.45), ztf.constant( 0.19), ztf.constant(0.857), ztf.constant(0.598), ztf.constant(0.531), ztf.constant(0.752), ztf.constant(0.229), ztf.constant(0,117)], + [ztf.constant( 0.45), ztf.constant( 1.), ztf.constant(0.677), ztf.constant(0.708), ztf.constant(0.958), ztf.constant(0.927), ztf.constant(0.227), ztf.constant(0.443), ztf.constant(0.287)], + [ztf.constant( 0.19), ztf.constant(0.677), ztf.constant( 1.), ztf.constant(0.595), ztf.constant(0.770), ztf.constant(0.819),ztf.constant(-0.023), ztf.constant( 0.07), ztf.constant(0.196)], + [ztf.constant(0.857), ztf.constant(0.708), ztf.constant(0.595), ztf.constant( 1.), ztf.constant( 0.83), ztf.constant(0.766), ztf.constant(0.582), ztf.constant(0.237), ztf.constant(0.192)], + [ztf.constant(0.598), ztf.constant(0.958), ztf.constant(0.770), ztf.constant( 0.83), ztf.constant( 1.), ztf.constant(0.973), ztf.constant(0.324), ztf.constant(0.372), ztf.constant(0.272)], + [ztf.constant(0.531), ztf.constant(0.927), ztf.constant(0.819), ztf.constant(0.766), ztf.constant(0.973), ztf.constant( 1.), ztf.constant(0.268), ztf.constant(0.332), ztf.constant(0.269)], + [ztf.constant(0.752), ztf.constant(0.227),ztf.constant(-0.023), ztf.constant(0.582), ztf.constant(0.324), ztf.constant(0.268), ztf.constant( 1.), ztf.constant( 0.59), ztf.constant(0.515)], + [ztf.constant(0.229), ztf.constant(0.443), ztf.constant( 0.07), ztf.constant(0.237), ztf.constant(0.372), ztf.constant(0.332), ztf.constant( 0.59), ztf.constant( 1.), ztf.constant(0.897)], + [ztf.constant(0.117), ztf.constant(0.287), ztf.constant(0.196), ztf.constant(0.192), ztf.constant(0.272), ztf.constant(0.269), ztf.constant(0.515), ztf.constant(0.897), ztf.constant( 1.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + w = x1*x1*(rho23*rho23-1) + x2*x2*(rho13*rho13-1)+x3*x3*(rho12*rho12-1)+2*(x1*x2*(rho12-rho13*rho23)+x1*x3*(rho13-rho12*rho23)+x2*x3*(rho23-rho12*rho13)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[ ]: + + +param_values_dic = { + 'jpsi_m': jpsi_mass, + 'jpsi_s': jpsi_scale, + 'jpsi_p': jpsi_phase, + 'jpsi_w': jpsi_width, + 'psi2s_m': psi2s_mass, + 'psi2s_s': psi2s_scale, + 'psi2s_p': psi2s_phase, + 'psi2s_w': psi2s_width, + 'p3770_m': p3770_mass, + 'p3770_s': p3770_scale, + 'p3770_p': p3770_phase, + 'p3770_w': p3770_width, + 'p4040_m': p4040_mass, + 'p4040_s': p4040_scale, + 'p4040_p': p4040_phase, + 'p4040_w': p4040_width, + 'p4160_m': p4160_mass, + 'p4160_s': p4160_scale, + 'p4160_p': p4160_phase, + 'p4160_w': p4160_width, + 'p4415_m': p4415_mass, + 'p4415_s': p4415_scale, + 'p4415_p': p4415_phase, + 'p4415_w': p4415_width, + 'rho_m': rho_mass, + 'rho_s': rho_scale, + 'rho_p': rho_phase, + 'rho_w': rho_width, + 'omega_m': omega_mass, + 'omega_s': omega_scale, + 'omega_p': omega_phase, + 'omega_w': omega_width, + 'phi_m': phi_mass, + 'phi_s': phi_scale, + 'phi_p': phi_phase, + 'phi_w': phi_width, + 'Dstar_m': Dstar_mass, + 'DDstar_s': 0.0, + 'DDstar_p': 0.0, + 'D_m': D_mass, + 'Dbar_m': Dbar_mass, + 'Dbar_s': 0.0, + 'Dbar_p': 0.0, + 'tau_m': pdg['tau_M'], + 'Ctt': 0.0, + 'b0_0': 0.292, + 'b0_1': 0.281, + 'b0_2': 0.150, + 'bplus_0': 0.466, + 'bplus_1': -0.885, + 'bplus_2': -0.213, + 'bT_0': 0.460, + 'bT_1': -1.089, + 'bT_2': -1.114} + + +def reset_param_values(variation = 0.05): + for param in total_f_fit.get_dependents(): + if param.floating: + param.set_value(param_values_dic[param.name] + random.uniform(-1, 1) * param_values_dic[param.name]* variation) +# print(param.name) +# for param in totalf.get_dependents(): +# param.set_value() + + +# # Analysis + +# In[ ]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[ ]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[ ]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[ ]: + + +# Ctt.floating = False + + +# In[ ]: + + +# zfit.run(nll.value()) + + +# In[ ]: + + +# result.fmin + + +# In[ ]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) +pull_dic = {} + +mi = 1e-4 +ma = 3e-3 +ste = 20 + +for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name] = [] + for step in range(2*ste): + pull_dic[param.name].append([]) + + + +def save_pulls(step): + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name][step].append((params[param]['value'] - param_values_dic[param.name])/params[param]['minuit_hesse']['error']) + + + +# for key in pull_dic.keys(): +# print(np.shape(pull_dic[key])) +# save_pulls(New_step=True) +# params[Ctt]['value'] + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(param.name) + +# print(params[Ctt]) + + +# # CLS Code + +# In[ ]: + + +# zfit.run.numeric_checks = False + +load = False + +bo = True + +D_contribs = True + +if not D_contribs: + Dbar_s.floating = False + Dbar_p.floating = False + DDstar_s.floating = False + DDstar_p.floating = False + +bo_set = 1 + +fitting_range = 'cut' +total_BR = 1.7e-10 + 4.9e-10 + 2.5e-9 + 6.02e-5 + 4.97e-6 + 1.38e-9 + 4.2e-10 + 2.6e-9 + 6.1e-10 + 4.37e-7 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +# mi = 1e-4 +# ma = 3e-3 +# ste = 13 + +BR_steps = np.linspace(mi, ma, ste) + +BR_steps[0] = 0.0 + +print(BR_steps) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +print(Ctt_steps) + +# total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents, fixed_params = False) +sampler.set_data_range(obs_fit) + +__ = -1 + +#----------------------------------------------------- + +if not load: + for Ctt_step in Ctt_steps: + + __ += 1 + + for i in range(2): + Ctt_list.append([]) + Ctt_error_list.append([]) + Nll_list.append([]) + + for param in total_f_fit.get_dependents(): + if param.floating: + pull_dic[param.name].append([]) + + for toy in range(nr_of_toys): + + newset = True + + while newset: + + for floaty in [True, False]: + Ctt.floating = floaty + + for bo_step in range(bo_set): + + print('Step: {0}/{1}'.format(int(__), ste)) + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + reset_param_values(variation = 0.0) + + if floaty: + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + Ctt.set_value(Ctt_step) + + else: + Ctt.set_value(0.0) + print('Toy {0}/{1} - Fit {2}/{3}'.format(toy, nr_of_toys, bo_step, bo_set)) + + if newset: + sampler.resample(n=nevents) + data = sampler + newset = False + + ### Fit data + + if floaty: + #plt.clf() + #plt.title('Ctt value: {:.2f}'.format(Ctt_step)) + #plt.hist(zfit.run(data), bins = int((x_max-x_min)/7), range = (x_min, x_max)) + #plt.savefig('data/CLs/plots/set_histo{}.png'.format(__)) + _step = 2*__ + else: + _step = 2*__+1 + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + print("Function minimum:", result.fmin) + print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + + save_pulls(step = _step) + + if floaty: + Nll_list[-2].append(result.fmin) + Ctt_list[-2].append(params[Ctt]['value']) + Ctt_error_list[-2].append(params[Ctt]['minuit_hesse']['error']) + + else: + Nll_list[-1].append(result.fmin) + Ctt_list[-1].append(0.0) + Ctt_error_list[-1].append(0.0) + + + else: + for _ in [1,2]: + del Nll_list[-_][toy*bo_set:] +# print(np.shape(Nll_list[-_])) + del Ctt_list[-_][toy*bo_set:] + del Ctt_error_list[-_][toy*bo_set:] + for param in total_f_fit.get_dependents(): + if param.floating: + del pull_dic[param.name][_step+1-_][toy*bo_set:] + newset = True + break + + if not result.converged: + break + + print() + print('Time taken: {}'.format(display_time(int(time.time()-start)))) + print('Estimated time left: {}'.format(display_time(int((time.time()-start)/(__+(toy+1)/nr_of_toys)*(ste-__-(nr_of_toys-toy-1)/nr_of_toys))))) + + +# In[ ]: + + +if load: + + phase_combi = '--' + + if D_contribs: + D_dir = 'D-True' + else: + D_dir = 'D-False' + + _dir = 'data/CLs/finished/f1d1/{}/{}/'.format(phase_combi, D_dir) + + jobs = os.listdir(_dir) + + First = True + +# print(jobs) + + for job in jobs: + + dirName = _dir + str(job) + '/data/CLs' + + if not os.path.exists("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys)): +# print(job) + continue + + with open(r"{}/variab.pkl".format(dirName), "rb") as input_file: + variab = pkl.load(input_file) +# print(variab) + + ### sanity check: + if variab['mi'] != mi or variab['ma'] != ma or variab['ste'] != ste or bo_set != bo_set: + print('Fitting parameters of data dont equal the ones given -- Job {} skipped!'.format(job)) + + with open(r"{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _Ctt_error_list = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "rb") as input_file: + _pull_dic = pkl.load(input_file) + + with open(r"{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "rb") as input_file: + _CLs_list = pkl.load(input_file) + + + if First: + Nll_list = _Nll_list + Ctt_list = _Ctt_list + Ctt_error_list = _Ctt_error_list + pull_dic = _pull_dic +# print(_pull_dic) + CLs_list = _CLs_list + First = False + else: + for step in range(2*ste): +# print(Nll_list[step], step) + Nll_list[step].extend(_Nll_list[step]) + Ctt_list[step].extend(_Ctt_list[step]) + Ctt_error_list[step].extend(_Ctt_error_list[step]) + for key in pull_dic.keys(): +# print(key, np.shape(pull_dic[key])) + pull_dic[key][step].extend(_pull_dic[key][step]) + for step in range(ste): + CLs_list[step].extend(_CLs_list[step]) + +# print('----------------------') + + +# In[ ]: + + +dirName = 'data/CLs' + +# if bo and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s{}b{}t--CLs_Nll_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--Ctt_error_list.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s{}b{}t--pull_dic.pkl".format(dirName, mi,ma,ste,bo_set,nr_of_toys), "wb") as f: + pkl.dump(pull_dic, f, pkl.HIGHEST_PROTOCOL) + + variab = {'mi': mi, + 'ma': ma, + 'ste': ste, + 'bo_set': bo_set, + 'nr_of_toys': nr_of_toys} + + with open("{}/variab.pkl".format(dirName), "wb") as f: + pkl.dump(variab, f, pkl.HIGHEST_PROTOCOL) + + CLs_values = [] + + toy_size = bo_set + + print(np.shape(Nll_list)) + print(Nll_list[0:1]) + + for step in range(ste): + CLs_values.append([]) + for toy in range(nr_of_toys): + float_min = np.min(Nll_list[2*step][toy*bo_set:(toy+1)*bo_set]) + fix_min = np.min(Nll_list[2*step+1][toy*bo_set:(toy+1)*bo_set]) + CLs_values[step].append(float_min-fix_min) + + + print(np.shape(CLs_values)) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[ ]: + + +# print(variab['mi'] != mi) + + +# ## Plot + +# In[ ]: + + +l = [] + + +if load: + CLs_values = -1*np.array(CLs_list) + +if not os.path.exists('data/CLs/plots'): + os.mkdir('data/CLs/plots') + print("Directory " , 'data/CLs/plots' , " Created ") + +print(np.shape(CLs_values)) + +for step in range(1,ste): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[step])) + plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0') + plt.hist(CLs_values[step], bins = 150, range = (-25, 50), label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[step])) + + l.append(len(np.where(np.array(CLs_values[step]) < np.mean(CLs_values[0]))[0])) + +for step in range(2*ste): + if step%2 == 0: + floaty = True + else: + floaty = False + for key in pull_dic.keys(): + if not os.path.exists('data/CLs/plots/{}'.format(key)): + os.mkdir('data/CLs/plots/{}'.format(key)) + plt.clf() + plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty)) + plt.hist(pull_dic[key][step], bins = 50, range = (-5,5)) + plt.xlabel('Pull') + plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty)) + + +# In[ ]: + + +for s in range(len(l)): + print('BR: {:.4f}'.format(BR_steps[s+1])) + print(2*l[s]/len(CLs_values[s])) + print() + + +# In[ ]: + + +# for step in range(2*ste): +# for key in pull_dic.keys(): +# print(pull_dic[key][step]) + + +# In[ ]: + + +# for param in total_f_fit.get_dependents(): +# if param.floating: +# print(params[param]['value']) + + +# In[ ]: + + +print(display_time(int(time.time()-start))) + + +# In[ ]: + + +# variab['mi'] =! mi + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + + +# In[ ]: + + + + 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 5e4ac8c..09b8e42 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.2E-03\051.png" "b/data/CLs/plots/CLs-BR\0501.2E-03\051.png" index f7dcf3d..af40ca0 100644 --- "a/data/CLs/plots/CLs-BR\0501.2E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.2E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0501.3E-03\051.png" "b/data/CLs/plots/CLs-BR\0501.3E-03\051.png" index f5394e8..5ebf063 100644 --- "a/data/CLs/plots/CLs-BR\0501.3E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.3E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0501.5E-03\051.png" "b/data/CLs/plots/CLs-BR\0501.5E-03\051.png" index adc557a..b0afa33 100644 --- "a/data/CLs/plots/CLs-BR\0501.5E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.5E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0501.6E-03\051.png" "b/data/CLs/plots/CLs-BR\0501.6E-03\051.png" index 19b4328..96cea33 100644 --- "a/data/CLs/plots/CLs-BR\0501.6E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.6E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0501.8E-03\051.png" "b/data/CLs/plots/CLs-BR\0501.8E-03\051.png" index 9f25ff2..da12d3a 100644 --- "a/data/CLs/plots/CLs-BR\0501.8E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.8E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0501.9E-03\051.png" "b/data/CLs/plots/CLs-BR\0501.9E-03\051.png" index b42ada2..3f6fba6 100644 --- "a/data/CLs/plots/CLs-BR\0501.9E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.9E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.1E-03\051.png" "b/data/CLs/plots/CLs-BR\0502.1E-03\051.png" index 8c03df1..673039b 100644 --- "a/data/CLs/plots/CLs-BR\0502.1E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.1E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.2E-03\051.png" "b/data/CLs/plots/CLs-BR\0502.2E-03\051.png" index a4c3da4..5388381 100644 --- "a/data/CLs/plots/CLs-BR\0502.2E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.2E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.4E-03\051.png" "b/data/CLs/plots/CLs-BR\0502.4E-03\051.png" index 7c7615d..e7b18b6 100644 --- "a/data/CLs/plots/CLs-BR\0502.4E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.4E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.5E-03\051.png" "b/data/CLs/plots/CLs-BR\0502.5E-03\051.png" index ef35267..837a666 100644 --- "a/data/CLs/plots/CLs-BR\0502.5E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.5E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.5E-04\051.png" "b/data/CLs/plots/CLs-BR\0502.5E-04\051.png" index 49fb82a..1ab52a0 100644 --- "a/data/CLs/plots/CLs-BR\0502.5E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.5E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.7E-03\051.png" "b/data/CLs/plots/CLs-BR\0502.7E-03\051.png" index bb00ed3..54ea244 100644 --- "a/data/CLs/plots/CLs-BR\0502.7E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.7E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.8E-03\051.png" "b/data/CLs/plots/CLs-BR\0502.8E-03\051.png" index b2d331d..0f542ec 100644 --- "a/data/CLs/plots/CLs-BR\0502.8E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.8E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0503.0E-03\051.png" "b/data/CLs/plots/CLs-BR\0503.0E-03\051.png" index 9b67afc..0d97697 100644 --- "a/data/CLs/plots/CLs-BR\0503.0E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0503.0E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0504.1E-04\051.png" "b/data/CLs/plots/CLs-BR\0504.1E-04\051.png" index c3eaff2..1d29d4b 100644 --- "a/data/CLs/plots/CLs-BR\0504.1E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0504.1E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0505.6E-04\051.png" "b/data/CLs/plots/CLs-BR\0505.6E-04\051.png" index 9a8bbe0..bced30d 100644 --- "a/data/CLs/plots/CLs-BR\0505.6E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0505.6E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0507.1E-04\051.png" "b/data/CLs/plots/CLs-BR\0507.1E-04\051.png" index 43a2ab2..0177df4 100644 --- "a/data/CLs/plots/CLs-BR\0507.1E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0507.1E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0508.6E-04\051.png" "b/data/CLs/plots/CLs-BR\0508.6E-04\051.png" index 3ffd272..5a2a344 100644 --- "a/data/CLs/plots/CLs-BR\0508.6E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0508.6E-04\051.png" Binary files differ diff --git a/data/CLs/plots/Ctt/0.00Ctt0sTruef.png b/data/CLs/plots/Ctt/0.00Ctt0sTruef.png index 6fcdce9..910036c 100644 --- a/data/CLs/plots/Ctt/0.00Ctt0sTruef.png +++ b/data/CLs/plots/Ctt/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.25Ctt2sTruef.png b/data/CLs/plots/Ctt/0.25Ctt2sTruef.png index 7478528..7742c30 100644 --- a/data/CLs/plots/Ctt/0.25Ctt2sTruef.png +++ b/data/CLs/plots/Ctt/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.31Ctt4sTruef.png b/data/CLs/plots/Ctt/0.31Ctt4sTruef.png index 86fd5ce..656baa9 100644 --- a/data/CLs/plots/Ctt/0.31Ctt4sTruef.png +++ b/data/CLs/plots/Ctt/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.36Ctt6sTruef.png b/data/CLs/plots/Ctt/0.36Ctt6sTruef.png index 8807fc6..4930cd3 100644 --- a/data/CLs/plots/Ctt/0.36Ctt6sTruef.png +++ b/data/CLs/plots/Ctt/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.41Ctt8sTruef.png b/data/CLs/plots/Ctt/0.41Ctt8sTruef.png index 099d3a6..c967b05 100644 --- a/data/CLs/plots/Ctt/0.41Ctt8sTruef.png +++ b/data/CLs/plots/Ctt/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.45Ctt10sTruef.png b/data/CLs/plots/Ctt/0.45Ctt10sTruef.png index 0cdf92b..ba89e68 100644 --- a/data/CLs/plots/Ctt/0.45Ctt10sTruef.png +++ b/data/CLs/plots/Ctt/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.49Ctt12sTruef.png b/data/CLs/plots/Ctt/0.49Ctt12sTruef.png index 523bee3..9d58e5f 100644 --- a/data/CLs/plots/Ctt/0.49Ctt12sTruef.png +++ b/data/CLs/plots/Ctt/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.53Ctt14sTruef.png b/data/CLs/plots/Ctt/0.53Ctt14sTruef.png index 374f9cf..a07e4d4 100644 --- a/data/CLs/plots/Ctt/0.53Ctt14sTruef.png +++ b/data/CLs/plots/Ctt/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.56Ctt16sTruef.png b/data/CLs/plots/Ctt/0.56Ctt16sTruef.png index a481819..05cdeca 100644 --- a/data/CLs/plots/Ctt/0.56Ctt16sTruef.png +++ b/data/CLs/plots/Ctt/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.59Ctt18sTruef.png b/data/CLs/plots/Ctt/0.59Ctt18sTruef.png index 0cd5009..b8241ce 100644 --- a/data/CLs/plots/Ctt/0.59Ctt18sTruef.png +++ b/data/CLs/plots/Ctt/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.62Ctt20sTruef.png b/data/CLs/plots/Ctt/0.62Ctt20sTruef.png index 9394a8b..fb0a68f 100644 --- a/data/CLs/plots/Ctt/0.62Ctt20sTruef.png +++ b/data/CLs/plots/Ctt/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.65Ctt22sTruef.png b/data/CLs/plots/Ctt/0.65Ctt22sTruef.png index d4d1b90..a196341 100644 --- a/data/CLs/plots/Ctt/0.65Ctt22sTruef.png +++ b/data/CLs/plots/Ctt/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.68Ctt24sTruef.png b/data/CLs/plots/Ctt/0.68Ctt24sTruef.png index e0f498a..5138aab 100644 --- a/data/CLs/plots/Ctt/0.68Ctt24sTruef.png +++ b/data/CLs/plots/Ctt/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.70Ctt26sTruef.png b/data/CLs/plots/Ctt/0.70Ctt26sTruef.png index fbf7063..11381fd 100644 --- a/data/CLs/plots/Ctt/0.70Ctt26sTruef.png +++ b/data/CLs/plots/Ctt/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.73Ctt28sTruef.png b/data/CLs/plots/Ctt/0.73Ctt28sTruef.png index de92410..7da37e8 100644 --- a/data/CLs/plots/Ctt/0.73Ctt28sTruef.png +++ b/data/CLs/plots/Ctt/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.75Ctt30sTruef.png b/data/CLs/plots/Ctt/0.75Ctt30sTruef.png index 05779e4..d68da96 100644 --- a/data/CLs/plots/Ctt/0.75Ctt30sTruef.png +++ b/data/CLs/plots/Ctt/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.78Ctt32sTruef.png b/data/CLs/plots/Ctt/0.78Ctt32sTruef.png index caa437b..cf03411 100644 --- a/data/CLs/plots/Ctt/0.78Ctt32sTruef.png +++ b/data/CLs/plots/Ctt/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.80Ctt34sTruef.png b/data/CLs/plots/Ctt/0.80Ctt34sTruef.png index 42dee6e..4a1945b 100644 --- a/data/CLs/plots/Ctt/0.80Ctt34sTruef.png +++ b/data/CLs/plots/Ctt/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.82Ctt36sTruef.png b/data/CLs/plots/Ctt/0.82Ctt36sTruef.png index 6908e9c..b017093 100644 --- a/data/CLs/plots/Ctt/0.82Ctt36sTruef.png +++ b/data/CLs/plots/Ctt/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/Ctt/0.85Ctt38sTruef.png b/data/CLs/plots/Ctt/0.85Ctt38sTruef.png index 3d04ed7..848b896 100644 --- a/data/CLs/plots/Ctt/0.85Ctt38sTruef.png +++ b/data/CLs/plots/Ctt/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.00Ctt0sTruef.png b/data/CLs/plots/DDstar_p/0.00Ctt0sTruef.png index cfc8eb7..7907b25 100644 --- a/data/CLs/plots/DDstar_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/DDstar_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.00Ctt1sFalsef.png b/data/CLs/plots/DDstar_p/0.00Ctt1sFalsef.png index d6717a7..0d5fdf6 100644 --- a/data/CLs/plots/DDstar_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.25Ctt2sTruef.png b/data/CLs/plots/DDstar_p/0.25Ctt2sTruef.png index b1311f8..4ea6b2e 100644 --- a/data/CLs/plots/DDstar_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/DDstar_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.25Ctt3sFalsef.png b/data/CLs/plots/DDstar_p/0.25Ctt3sFalsef.png index 4f5021c..46b57f7 100644 --- a/data/CLs/plots/DDstar_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.31Ctt4sTruef.png b/data/CLs/plots/DDstar_p/0.31Ctt4sTruef.png index f0e02a8..9a5e8da 100644 --- a/data/CLs/plots/DDstar_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/DDstar_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.31Ctt5sFalsef.png b/data/CLs/plots/DDstar_p/0.31Ctt5sFalsef.png index 8d637b7..b3b54e3 100644 --- a/data/CLs/plots/DDstar_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.36Ctt6sTruef.png b/data/CLs/plots/DDstar_p/0.36Ctt6sTruef.png index c4d8daf..dc773da 100644 --- a/data/CLs/plots/DDstar_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/DDstar_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.36Ctt7sFalsef.png b/data/CLs/plots/DDstar_p/0.36Ctt7sFalsef.png index e2011c1..63181ba 100644 --- a/data/CLs/plots/DDstar_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.41Ctt8sTruef.png b/data/CLs/plots/DDstar_p/0.41Ctt8sTruef.png index fe7909c..1945749 100644 --- a/data/CLs/plots/DDstar_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/DDstar_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.41Ctt9sFalsef.png b/data/CLs/plots/DDstar_p/0.41Ctt9sFalsef.png index fd08cbf..a978cd8 100644 --- a/data/CLs/plots/DDstar_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.45Ctt10sTruef.png b/data/CLs/plots/DDstar_p/0.45Ctt10sTruef.png index 767edc0..d77ada6 100644 --- a/data/CLs/plots/DDstar_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/DDstar_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.45Ctt11sFalsef.png b/data/CLs/plots/DDstar_p/0.45Ctt11sFalsef.png index 7fa87ed..02b751a 100644 --- a/data/CLs/plots/DDstar_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.49Ctt12sTruef.png b/data/CLs/plots/DDstar_p/0.49Ctt12sTruef.png index 30b5372..0f61c6e 100644 --- a/data/CLs/plots/DDstar_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/DDstar_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.49Ctt13sFalsef.png b/data/CLs/plots/DDstar_p/0.49Ctt13sFalsef.png index 7f22ea6..6e2ab6b 100644 --- a/data/CLs/plots/DDstar_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.53Ctt14sTruef.png b/data/CLs/plots/DDstar_p/0.53Ctt14sTruef.png index c6c96de..58e3057 100644 --- a/data/CLs/plots/DDstar_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/DDstar_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.53Ctt15sFalsef.png b/data/CLs/plots/DDstar_p/0.53Ctt15sFalsef.png index 17765c5..10e1922 100644 --- a/data/CLs/plots/DDstar_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.56Ctt16sTruef.png b/data/CLs/plots/DDstar_p/0.56Ctt16sTruef.png index e8ae9c9..78ca167 100644 --- a/data/CLs/plots/DDstar_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/DDstar_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.56Ctt17sFalsef.png b/data/CLs/plots/DDstar_p/0.56Ctt17sFalsef.png index 8b42e7f..fbdde1e 100644 --- a/data/CLs/plots/DDstar_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.59Ctt18sTruef.png b/data/CLs/plots/DDstar_p/0.59Ctt18sTruef.png index 66cfd9f..06cb80c 100644 --- a/data/CLs/plots/DDstar_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/DDstar_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.59Ctt19sFalsef.png b/data/CLs/plots/DDstar_p/0.59Ctt19sFalsef.png index c75c08c..9b71a64 100644 --- a/data/CLs/plots/DDstar_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.62Ctt20sTruef.png b/data/CLs/plots/DDstar_p/0.62Ctt20sTruef.png index 6f649ae..e763d44 100644 --- a/data/CLs/plots/DDstar_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/DDstar_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.62Ctt21sFalsef.png b/data/CLs/plots/DDstar_p/0.62Ctt21sFalsef.png index b498440..4f76145 100644 --- a/data/CLs/plots/DDstar_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.65Ctt22sTruef.png b/data/CLs/plots/DDstar_p/0.65Ctt22sTruef.png index ff7123b..8b07e44 100644 --- a/data/CLs/plots/DDstar_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/DDstar_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.65Ctt23sFalsef.png b/data/CLs/plots/DDstar_p/0.65Ctt23sFalsef.png index 265c865..bda0050 100644 --- a/data/CLs/plots/DDstar_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.68Ctt24sTruef.png b/data/CLs/plots/DDstar_p/0.68Ctt24sTruef.png index c55b727..bc24338 100644 --- a/data/CLs/plots/DDstar_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/DDstar_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.68Ctt25sFalsef.png b/data/CLs/plots/DDstar_p/0.68Ctt25sFalsef.png index 1965ecc..f1da54e 100644 --- a/data/CLs/plots/DDstar_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.70Ctt26sTruef.png b/data/CLs/plots/DDstar_p/0.70Ctt26sTruef.png index 72d1f8a..32fe6b6 100644 --- a/data/CLs/plots/DDstar_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/DDstar_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.70Ctt27sFalsef.png b/data/CLs/plots/DDstar_p/0.70Ctt27sFalsef.png index 15b9d96..c17d669 100644 --- a/data/CLs/plots/DDstar_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.73Ctt28sTruef.png b/data/CLs/plots/DDstar_p/0.73Ctt28sTruef.png index 28fb5e8..de0e9d5 100644 --- a/data/CLs/plots/DDstar_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/DDstar_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.73Ctt29sFalsef.png b/data/CLs/plots/DDstar_p/0.73Ctt29sFalsef.png index fd47f0e..dc3ca5c 100644 --- a/data/CLs/plots/DDstar_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.75Ctt30sTruef.png b/data/CLs/plots/DDstar_p/0.75Ctt30sTruef.png index 5f8f1bf..16f6f44 100644 --- a/data/CLs/plots/DDstar_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/DDstar_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.75Ctt31sFalsef.png b/data/CLs/plots/DDstar_p/0.75Ctt31sFalsef.png index 8c7535f..c08ba7c 100644 --- a/data/CLs/plots/DDstar_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.78Ctt32sTruef.png b/data/CLs/plots/DDstar_p/0.78Ctt32sTruef.png index 04c15dc..e85aa67 100644 --- a/data/CLs/plots/DDstar_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/DDstar_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.78Ctt33sFalsef.png b/data/CLs/plots/DDstar_p/0.78Ctt33sFalsef.png index 53ae066..2a792c5 100644 --- a/data/CLs/plots/DDstar_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.80Ctt34sTruef.png b/data/CLs/plots/DDstar_p/0.80Ctt34sTruef.png index 97a4251..041a8fd 100644 --- a/data/CLs/plots/DDstar_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/DDstar_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.80Ctt35sFalsef.png b/data/CLs/plots/DDstar_p/0.80Ctt35sFalsef.png index d3b2ca2..e270a6b 100644 --- a/data/CLs/plots/DDstar_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.82Ctt36sTruef.png b/data/CLs/plots/DDstar_p/0.82Ctt36sTruef.png index 80278c1..7197acf 100644 --- a/data/CLs/plots/DDstar_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/DDstar_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.82Ctt37sFalsef.png b/data/CLs/plots/DDstar_p/0.82Ctt37sFalsef.png index 2af18d4..641edad 100644 --- a/data/CLs/plots/DDstar_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.85Ctt38sTruef.png b/data/CLs/plots/DDstar_p/0.85Ctt38sTruef.png index ae29ed1..0463f5b 100644 --- a/data/CLs/plots/DDstar_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/DDstar_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_p/0.85Ctt39sFalsef.png b/data/CLs/plots/DDstar_p/0.85Ctt39sFalsef.png index 9bd69d9..81f6d0d 100644 --- a/data/CLs/plots/DDstar_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/DDstar_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.00Ctt0sTruef.png b/data/CLs/plots/DDstar_s/0.00Ctt0sTruef.png index 881c4c8..3faa881 100644 --- a/data/CLs/plots/DDstar_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/DDstar_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.00Ctt1sFalsef.png b/data/CLs/plots/DDstar_s/0.00Ctt1sFalsef.png index 16d2c06..174a371 100644 --- a/data/CLs/plots/DDstar_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.25Ctt2sTruef.png b/data/CLs/plots/DDstar_s/0.25Ctt2sTruef.png index bc6f399..b7b6bbf 100644 --- a/data/CLs/plots/DDstar_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/DDstar_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.25Ctt3sFalsef.png b/data/CLs/plots/DDstar_s/0.25Ctt3sFalsef.png index 66a3709..babb0bc 100644 --- a/data/CLs/plots/DDstar_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.31Ctt4sTruef.png b/data/CLs/plots/DDstar_s/0.31Ctt4sTruef.png index d34376a..a088d9b 100644 --- a/data/CLs/plots/DDstar_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/DDstar_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.31Ctt5sFalsef.png b/data/CLs/plots/DDstar_s/0.31Ctt5sFalsef.png index 4dd750a..b04b24d 100644 --- a/data/CLs/plots/DDstar_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.36Ctt6sTruef.png b/data/CLs/plots/DDstar_s/0.36Ctt6sTruef.png index f76a825..b874a52 100644 --- a/data/CLs/plots/DDstar_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/DDstar_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.36Ctt7sFalsef.png b/data/CLs/plots/DDstar_s/0.36Ctt7sFalsef.png index c69d130..50f0961 100644 --- a/data/CLs/plots/DDstar_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.41Ctt8sTruef.png b/data/CLs/plots/DDstar_s/0.41Ctt8sTruef.png index 214fe88..703819f 100644 --- a/data/CLs/plots/DDstar_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/DDstar_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.41Ctt9sFalsef.png b/data/CLs/plots/DDstar_s/0.41Ctt9sFalsef.png index 46eb5d2..eead53e 100644 --- a/data/CLs/plots/DDstar_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.45Ctt10sTruef.png b/data/CLs/plots/DDstar_s/0.45Ctt10sTruef.png index f14357c..fb7c6bf 100644 --- a/data/CLs/plots/DDstar_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/DDstar_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.45Ctt11sFalsef.png b/data/CLs/plots/DDstar_s/0.45Ctt11sFalsef.png index f927dbf..074a783 100644 --- a/data/CLs/plots/DDstar_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.49Ctt12sTruef.png b/data/CLs/plots/DDstar_s/0.49Ctt12sTruef.png index fbcb4d3..61d9a3a 100644 --- a/data/CLs/plots/DDstar_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/DDstar_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.49Ctt13sFalsef.png b/data/CLs/plots/DDstar_s/0.49Ctt13sFalsef.png index 03c9dca..92e39ff 100644 --- a/data/CLs/plots/DDstar_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.53Ctt14sTruef.png b/data/CLs/plots/DDstar_s/0.53Ctt14sTruef.png index 512371a..0c9598b 100644 --- a/data/CLs/plots/DDstar_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/DDstar_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.53Ctt15sFalsef.png b/data/CLs/plots/DDstar_s/0.53Ctt15sFalsef.png index f33620b..25bd756 100644 --- a/data/CLs/plots/DDstar_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.56Ctt16sTruef.png b/data/CLs/plots/DDstar_s/0.56Ctt16sTruef.png index 5ca6ebf..9a19788 100644 --- a/data/CLs/plots/DDstar_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/DDstar_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.56Ctt17sFalsef.png b/data/CLs/plots/DDstar_s/0.56Ctt17sFalsef.png index bfd14ee..5f02ade 100644 --- a/data/CLs/plots/DDstar_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.59Ctt18sTruef.png b/data/CLs/plots/DDstar_s/0.59Ctt18sTruef.png index 3f4b7c9..b73fa96 100644 --- a/data/CLs/plots/DDstar_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/DDstar_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.59Ctt19sFalsef.png b/data/CLs/plots/DDstar_s/0.59Ctt19sFalsef.png index 73124cc..4adc347 100644 --- a/data/CLs/plots/DDstar_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.62Ctt20sTruef.png b/data/CLs/plots/DDstar_s/0.62Ctt20sTruef.png index c8e9e71..59b2e4c 100644 --- a/data/CLs/plots/DDstar_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/DDstar_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.62Ctt21sFalsef.png b/data/CLs/plots/DDstar_s/0.62Ctt21sFalsef.png index db193fe..3202b24 100644 --- a/data/CLs/plots/DDstar_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.65Ctt22sTruef.png b/data/CLs/plots/DDstar_s/0.65Ctt22sTruef.png index 00fbc28..1502401 100644 --- a/data/CLs/plots/DDstar_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/DDstar_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.65Ctt23sFalsef.png b/data/CLs/plots/DDstar_s/0.65Ctt23sFalsef.png index e943eb3..2e24196 100644 --- a/data/CLs/plots/DDstar_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.68Ctt24sTruef.png b/data/CLs/plots/DDstar_s/0.68Ctt24sTruef.png index c8159d2..5621c60 100644 --- a/data/CLs/plots/DDstar_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/DDstar_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.68Ctt25sFalsef.png b/data/CLs/plots/DDstar_s/0.68Ctt25sFalsef.png index 101eb98..4235b6b 100644 --- a/data/CLs/plots/DDstar_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.70Ctt26sTruef.png b/data/CLs/plots/DDstar_s/0.70Ctt26sTruef.png index 91c009d..e67ee60 100644 --- a/data/CLs/plots/DDstar_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/DDstar_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.70Ctt27sFalsef.png b/data/CLs/plots/DDstar_s/0.70Ctt27sFalsef.png index 9fe95c5..50d357c 100644 --- a/data/CLs/plots/DDstar_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.73Ctt28sTruef.png b/data/CLs/plots/DDstar_s/0.73Ctt28sTruef.png index 461ade9..a9b19fd 100644 --- a/data/CLs/plots/DDstar_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/DDstar_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.73Ctt29sFalsef.png b/data/CLs/plots/DDstar_s/0.73Ctt29sFalsef.png index 5fd8e53..66d2b72 100644 --- a/data/CLs/plots/DDstar_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.75Ctt30sTruef.png b/data/CLs/plots/DDstar_s/0.75Ctt30sTruef.png index b4170ab..85a62f5 100644 --- a/data/CLs/plots/DDstar_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/DDstar_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.75Ctt31sFalsef.png b/data/CLs/plots/DDstar_s/0.75Ctt31sFalsef.png index 26509b7..6cd8f7c 100644 --- a/data/CLs/plots/DDstar_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.78Ctt32sTruef.png b/data/CLs/plots/DDstar_s/0.78Ctt32sTruef.png index f375753..ac20dcb 100644 --- a/data/CLs/plots/DDstar_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/DDstar_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.78Ctt33sFalsef.png b/data/CLs/plots/DDstar_s/0.78Ctt33sFalsef.png index ed49218..ad7f6d4 100644 --- a/data/CLs/plots/DDstar_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.80Ctt34sTruef.png b/data/CLs/plots/DDstar_s/0.80Ctt34sTruef.png index 0a1e882..ed540a2 100644 --- a/data/CLs/plots/DDstar_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/DDstar_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.80Ctt35sFalsef.png b/data/CLs/plots/DDstar_s/0.80Ctt35sFalsef.png index f5fb038..38bce66 100644 --- a/data/CLs/plots/DDstar_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.82Ctt36sTruef.png b/data/CLs/plots/DDstar_s/0.82Ctt36sTruef.png index 856e635..2db1fd8 100644 --- a/data/CLs/plots/DDstar_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/DDstar_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.82Ctt37sFalsef.png b/data/CLs/plots/DDstar_s/0.82Ctt37sFalsef.png index a0b120c..0a2ac72 100644 --- a/data/CLs/plots/DDstar_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.85Ctt38sTruef.png b/data/CLs/plots/DDstar_s/0.85Ctt38sTruef.png index 6b3caf2..5e7ac45 100644 --- a/data/CLs/plots/DDstar_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/DDstar_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/DDstar_s/0.85Ctt39sFalsef.png b/data/CLs/plots/DDstar_s/0.85Ctt39sFalsef.png index 2ad6cdb..ffca536 100644 --- a/data/CLs/plots/DDstar_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/DDstar_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.00Ctt0sTruef.png b/data/CLs/plots/Dbar_p/0.00Ctt0sTruef.png index 12e8a7e..f541a55 100644 --- a/data/CLs/plots/Dbar_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/Dbar_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.00Ctt1sFalsef.png b/data/CLs/plots/Dbar_p/0.00Ctt1sFalsef.png index e4e9a67..9303e8d 100644 --- a/data/CLs/plots/Dbar_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.25Ctt2sTruef.png b/data/CLs/plots/Dbar_p/0.25Ctt2sTruef.png index 0ea56b7..45fd4f5 100644 --- a/data/CLs/plots/Dbar_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/Dbar_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.25Ctt3sFalsef.png b/data/CLs/plots/Dbar_p/0.25Ctt3sFalsef.png index 6f090b0..8f69784 100644 --- a/data/CLs/plots/Dbar_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.31Ctt4sTruef.png b/data/CLs/plots/Dbar_p/0.31Ctt4sTruef.png index c821518..6204b0b 100644 --- a/data/CLs/plots/Dbar_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/Dbar_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.31Ctt5sFalsef.png b/data/CLs/plots/Dbar_p/0.31Ctt5sFalsef.png index a1a87ac..6c9535e 100644 --- a/data/CLs/plots/Dbar_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.36Ctt6sTruef.png b/data/CLs/plots/Dbar_p/0.36Ctt6sTruef.png index 763129b..afd2218 100644 --- a/data/CLs/plots/Dbar_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/Dbar_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.36Ctt7sFalsef.png b/data/CLs/plots/Dbar_p/0.36Ctt7sFalsef.png index c43244d..ce67b07 100644 --- a/data/CLs/plots/Dbar_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.41Ctt8sTruef.png b/data/CLs/plots/Dbar_p/0.41Ctt8sTruef.png index 33e1771..6e63e59 100644 --- a/data/CLs/plots/Dbar_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/Dbar_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.41Ctt9sFalsef.png b/data/CLs/plots/Dbar_p/0.41Ctt9sFalsef.png index d9f1d5b..dd5ccfa 100644 --- a/data/CLs/plots/Dbar_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.45Ctt10sTruef.png b/data/CLs/plots/Dbar_p/0.45Ctt10sTruef.png index 0fe8e31..5509b82 100644 --- a/data/CLs/plots/Dbar_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/Dbar_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.45Ctt11sFalsef.png b/data/CLs/plots/Dbar_p/0.45Ctt11sFalsef.png index 89d4569..1323be5 100644 --- a/data/CLs/plots/Dbar_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.49Ctt12sTruef.png b/data/CLs/plots/Dbar_p/0.49Ctt12sTruef.png index 955e0bd..ccf5bf3 100644 --- a/data/CLs/plots/Dbar_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/Dbar_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.49Ctt13sFalsef.png b/data/CLs/plots/Dbar_p/0.49Ctt13sFalsef.png index 8780be1..b61d093 100644 --- a/data/CLs/plots/Dbar_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.53Ctt14sTruef.png b/data/CLs/plots/Dbar_p/0.53Ctt14sTruef.png index 7514784..b0cc230 100644 --- a/data/CLs/plots/Dbar_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/Dbar_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.53Ctt15sFalsef.png b/data/CLs/plots/Dbar_p/0.53Ctt15sFalsef.png index ce2ac8e..21da3b1 100644 --- a/data/CLs/plots/Dbar_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.56Ctt16sTruef.png b/data/CLs/plots/Dbar_p/0.56Ctt16sTruef.png index 6c6e455..0c74dd6 100644 --- a/data/CLs/plots/Dbar_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/Dbar_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.56Ctt17sFalsef.png b/data/CLs/plots/Dbar_p/0.56Ctt17sFalsef.png index 001cf10..e32a063 100644 --- a/data/CLs/plots/Dbar_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.59Ctt18sTruef.png b/data/CLs/plots/Dbar_p/0.59Ctt18sTruef.png index d8b99fd..2ff3867 100644 --- a/data/CLs/plots/Dbar_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/Dbar_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.59Ctt19sFalsef.png b/data/CLs/plots/Dbar_p/0.59Ctt19sFalsef.png index d4df8ac..fc15542 100644 --- a/data/CLs/plots/Dbar_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.62Ctt20sTruef.png b/data/CLs/plots/Dbar_p/0.62Ctt20sTruef.png index 0c78fbb..281acba 100644 --- a/data/CLs/plots/Dbar_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/Dbar_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.62Ctt21sFalsef.png b/data/CLs/plots/Dbar_p/0.62Ctt21sFalsef.png index 795489c..bc400f5 100644 --- a/data/CLs/plots/Dbar_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.65Ctt22sTruef.png b/data/CLs/plots/Dbar_p/0.65Ctt22sTruef.png index 761f193..0b29364 100644 --- a/data/CLs/plots/Dbar_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/Dbar_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.65Ctt23sFalsef.png b/data/CLs/plots/Dbar_p/0.65Ctt23sFalsef.png index e81dec4..9455d95 100644 --- a/data/CLs/plots/Dbar_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.68Ctt24sTruef.png b/data/CLs/plots/Dbar_p/0.68Ctt24sTruef.png index 1da2aed..0778f6b 100644 --- a/data/CLs/plots/Dbar_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/Dbar_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.68Ctt25sFalsef.png b/data/CLs/plots/Dbar_p/0.68Ctt25sFalsef.png index beb8d15..402049c 100644 --- a/data/CLs/plots/Dbar_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.70Ctt26sTruef.png b/data/CLs/plots/Dbar_p/0.70Ctt26sTruef.png index ff11040..bdafc78 100644 --- a/data/CLs/plots/Dbar_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/Dbar_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.70Ctt27sFalsef.png b/data/CLs/plots/Dbar_p/0.70Ctt27sFalsef.png index 4bab291..0bf684b 100644 --- a/data/CLs/plots/Dbar_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.73Ctt28sTruef.png b/data/CLs/plots/Dbar_p/0.73Ctt28sTruef.png index b7579f1..07b02e5 100644 --- a/data/CLs/plots/Dbar_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/Dbar_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.73Ctt29sFalsef.png b/data/CLs/plots/Dbar_p/0.73Ctt29sFalsef.png index e0a0b3f..2265eba 100644 --- a/data/CLs/plots/Dbar_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.75Ctt30sTruef.png b/data/CLs/plots/Dbar_p/0.75Ctt30sTruef.png index 4d560c7..60c4a94 100644 --- a/data/CLs/plots/Dbar_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/Dbar_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.75Ctt31sFalsef.png b/data/CLs/plots/Dbar_p/0.75Ctt31sFalsef.png index f06f431..a0f6ebd 100644 --- a/data/CLs/plots/Dbar_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.78Ctt32sTruef.png b/data/CLs/plots/Dbar_p/0.78Ctt32sTruef.png index b7ef02b..dae5639 100644 --- a/data/CLs/plots/Dbar_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/Dbar_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.78Ctt33sFalsef.png b/data/CLs/plots/Dbar_p/0.78Ctt33sFalsef.png index e3d9a70..3674f1e 100644 --- a/data/CLs/plots/Dbar_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.80Ctt34sTruef.png b/data/CLs/plots/Dbar_p/0.80Ctt34sTruef.png index 25ec8c1..36b8f38 100644 --- a/data/CLs/plots/Dbar_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/Dbar_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.80Ctt35sFalsef.png b/data/CLs/plots/Dbar_p/0.80Ctt35sFalsef.png index 83f2d50..7a399b8 100644 --- a/data/CLs/plots/Dbar_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.82Ctt36sTruef.png b/data/CLs/plots/Dbar_p/0.82Ctt36sTruef.png index ec2bddf..b148954 100644 --- a/data/CLs/plots/Dbar_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/Dbar_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.82Ctt37sFalsef.png b/data/CLs/plots/Dbar_p/0.82Ctt37sFalsef.png index ddc7457..e1a6bfd 100644 --- a/data/CLs/plots/Dbar_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.85Ctt38sTruef.png b/data/CLs/plots/Dbar_p/0.85Ctt38sTruef.png index b489ef0..0dbde63 100644 --- a/data/CLs/plots/Dbar_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/Dbar_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_p/0.85Ctt39sFalsef.png b/data/CLs/plots/Dbar_p/0.85Ctt39sFalsef.png index d432f7a..59ea4c3 100644 --- a/data/CLs/plots/Dbar_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/Dbar_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.00Ctt0sTruef.png b/data/CLs/plots/Dbar_s/0.00Ctt0sTruef.png index d28533e..73e1fc8 100644 --- a/data/CLs/plots/Dbar_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/Dbar_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.00Ctt1sFalsef.png b/data/CLs/plots/Dbar_s/0.00Ctt1sFalsef.png index caa15ec..84999d1 100644 --- a/data/CLs/plots/Dbar_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.25Ctt2sTruef.png b/data/CLs/plots/Dbar_s/0.25Ctt2sTruef.png index 9e9b8c6..be29305 100644 --- a/data/CLs/plots/Dbar_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/Dbar_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.25Ctt3sFalsef.png b/data/CLs/plots/Dbar_s/0.25Ctt3sFalsef.png index a2ac882..ad97d82 100644 --- a/data/CLs/plots/Dbar_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.31Ctt4sTruef.png b/data/CLs/plots/Dbar_s/0.31Ctt4sTruef.png index 435cf8d..661e39e 100644 --- a/data/CLs/plots/Dbar_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/Dbar_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.31Ctt5sFalsef.png b/data/CLs/plots/Dbar_s/0.31Ctt5sFalsef.png index 40cc41e..7c7a186 100644 --- a/data/CLs/plots/Dbar_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.36Ctt6sTruef.png b/data/CLs/plots/Dbar_s/0.36Ctt6sTruef.png index 86db006..8a14d82 100644 --- a/data/CLs/plots/Dbar_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/Dbar_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.36Ctt7sFalsef.png b/data/CLs/plots/Dbar_s/0.36Ctt7sFalsef.png index 450d575..ea176e6 100644 --- a/data/CLs/plots/Dbar_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.41Ctt8sTruef.png b/data/CLs/plots/Dbar_s/0.41Ctt8sTruef.png index 85789a7..dee6c66 100644 --- a/data/CLs/plots/Dbar_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/Dbar_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.41Ctt9sFalsef.png b/data/CLs/plots/Dbar_s/0.41Ctt9sFalsef.png index ba225d9..c09f332 100644 --- a/data/CLs/plots/Dbar_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.45Ctt10sTruef.png b/data/CLs/plots/Dbar_s/0.45Ctt10sTruef.png index bdbf2cd..a36bde6 100644 --- a/data/CLs/plots/Dbar_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/Dbar_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.45Ctt11sFalsef.png b/data/CLs/plots/Dbar_s/0.45Ctt11sFalsef.png index 4d924ac..b6d3ea2 100644 --- a/data/CLs/plots/Dbar_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.49Ctt12sTruef.png b/data/CLs/plots/Dbar_s/0.49Ctt12sTruef.png index 83f281a..05a33d3 100644 --- a/data/CLs/plots/Dbar_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/Dbar_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.49Ctt13sFalsef.png b/data/CLs/plots/Dbar_s/0.49Ctt13sFalsef.png index 82f5141..268239f 100644 --- a/data/CLs/plots/Dbar_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.53Ctt14sTruef.png b/data/CLs/plots/Dbar_s/0.53Ctt14sTruef.png index 45c6d09..550855d 100644 --- a/data/CLs/plots/Dbar_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/Dbar_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.53Ctt15sFalsef.png b/data/CLs/plots/Dbar_s/0.53Ctt15sFalsef.png index b08a960..0e6c94a 100644 --- a/data/CLs/plots/Dbar_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.56Ctt16sTruef.png b/data/CLs/plots/Dbar_s/0.56Ctt16sTruef.png index 97eb935..976d620 100644 --- a/data/CLs/plots/Dbar_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/Dbar_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.56Ctt17sFalsef.png b/data/CLs/plots/Dbar_s/0.56Ctt17sFalsef.png index ce11809..ea30c3b 100644 --- a/data/CLs/plots/Dbar_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.59Ctt18sTruef.png b/data/CLs/plots/Dbar_s/0.59Ctt18sTruef.png index eb812a8..318edd0 100644 --- a/data/CLs/plots/Dbar_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/Dbar_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.59Ctt19sFalsef.png b/data/CLs/plots/Dbar_s/0.59Ctt19sFalsef.png index 14cc83d..0c00ee1 100644 --- a/data/CLs/plots/Dbar_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.62Ctt20sTruef.png b/data/CLs/plots/Dbar_s/0.62Ctt20sTruef.png index d249eeb..1d209bd 100644 --- a/data/CLs/plots/Dbar_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/Dbar_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.62Ctt21sFalsef.png b/data/CLs/plots/Dbar_s/0.62Ctt21sFalsef.png index c4d33b7..9a96a34 100644 --- a/data/CLs/plots/Dbar_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.65Ctt22sTruef.png b/data/CLs/plots/Dbar_s/0.65Ctt22sTruef.png index c985e1f..576b3bd 100644 --- a/data/CLs/plots/Dbar_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/Dbar_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.65Ctt23sFalsef.png b/data/CLs/plots/Dbar_s/0.65Ctt23sFalsef.png index 8409e4a..135c700 100644 --- a/data/CLs/plots/Dbar_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.68Ctt24sTruef.png b/data/CLs/plots/Dbar_s/0.68Ctt24sTruef.png index ddf8782..539af06 100644 --- a/data/CLs/plots/Dbar_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/Dbar_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.68Ctt25sFalsef.png b/data/CLs/plots/Dbar_s/0.68Ctt25sFalsef.png index 8da93bc..c6c21f7 100644 --- a/data/CLs/plots/Dbar_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.70Ctt26sTruef.png b/data/CLs/plots/Dbar_s/0.70Ctt26sTruef.png index 0e3e19f..b0e66cc 100644 --- a/data/CLs/plots/Dbar_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/Dbar_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.70Ctt27sFalsef.png b/data/CLs/plots/Dbar_s/0.70Ctt27sFalsef.png index 6e1c8ec..6614ce9 100644 --- a/data/CLs/plots/Dbar_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.73Ctt28sTruef.png b/data/CLs/plots/Dbar_s/0.73Ctt28sTruef.png index 92914ac..02d318b 100644 --- a/data/CLs/plots/Dbar_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/Dbar_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.73Ctt29sFalsef.png b/data/CLs/plots/Dbar_s/0.73Ctt29sFalsef.png index 372c48b..dfabdf9 100644 --- a/data/CLs/plots/Dbar_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.75Ctt30sTruef.png b/data/CLs/plots/Dbar_s/0.75Ctt30sTruef.png index ccea1e2..9439555 100644 --- a/data/CLs/plots/Dbar_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/Dbar_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.75Ctt31sFalsef.png b/data/CLs/plots/Dbar_s/0.75Ctt31sFalsef.png index a3c1ea7..c0c53ac 100644 --- a/data/CLs/plots/Dbar_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.78Ctt32sTruef.png b/data/CLs/plots/Dbar_s/0.78Ctt32sTruef.png index dc75df7..597fcab 100644 --- a/data/CLs/plots/Dbar_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/Dbar_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.78Ctt33sFalsef.png b/data/CLs/plots/Dbar_s/0.78Ctt33sFalsef.png index aafb49f..8736a98 100644 --- a/data/CLs/plots/Dbar_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.80Ctt34sTruef.png b/data/CLs/plots/Dbar_s/0.80Ctt34sTruef.png index d6b9a1a..e056531 100644 --- a/data/CLs/plots/Dbar_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/Dbar_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.80Ctt35sFalsef.png b/data/CLs/plots/Dbar_s/0.80Ctt35sFalsef.png index 63b4478..c67ff34 100644 --- a/data/CLs/plots/Dbar_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.82Ctt36sTruef.png b/data/CLs/plots/Dbar_s/0.82Ctt36sTruef.png index 3ca22da..174ff45 100644 --- a/data/CLs/plots/Dbar_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/Dbar_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.82Ctt37sFalsef.png b/data/CLs/plots/Dbar_s/0.82Ctt37sFalsef.png index 6d8dc2c..63cf2de 100644 --- a/data/CLs/plots/Dbar_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.85Ctt38sTruef.png b/data/CLs/plots/Dbar_s/0.85Ctt38sTruef.png index ec30dd7..98cbd0c 100644 --- a/data/CLs/plots/Dbar_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/Dbar_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/Dbar_s/0.85Ctt39sFalsef.png b/data/CLs/plots/Dbar_s/0.85Ctt39sFalsef.png index e91c7f6..ad6707e 100644 --- a/data/CLs/plots/Dbar_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/Dbar_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.00Ctt0sTruef.png b/data/CLs/plots/bplus_0/0.00Ctt0sTruef.png index 8bf7b6f..f4c74d2 100644 --- a/data/CLs/plots/bplus_0/0.00Ctt0sTruef.png +++ b/data/CLs/plots/bplus_0/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.00Ctt1sFalsef.png b/data/CLs/plots/bplus_0/0.00Ctt1sFalsef.png index 8a38d1c..0f82a62 100644 --- a/data/CLs/plots/bplus_0/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/bplus_0/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.25Ctt2sTruef.png b/data/CLs/plots/bplus_0/0.25Ctt2sTruef.png index 72fdda2..a03464c 100644 --- a/data/CLs/plots/bplus_0/0.25Ctt2sTruef.png +++ b/data/CLs/plots/bplus_0/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.25Ctt3sFalsef.png b/data/CLs/plots/bplus_0/0.25Ctt3sFalsef.png index c1b8edd..1725ef5 100644 --- a/data/CLs/plots/bplus_0/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/bplus_0/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.31Ctt4sTruef.png b/data/CLs/plots/bplus_0/0.31Ctt4sTruef.png index d816aa4..015e5fc 100644 --- a/data/CLs/plots/bplus_0/0.31Ctt4sTruef.png +++ b/data/CLs/plots/bplus_0/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.31Ctt5sFalsef.png b/data/CLs/plots/bplus_0/0.31Ctt5sFalsef.png index e6559eb..3b7a74a 100644 --- a/data/CLs/plots/bplus_0/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/bplus_0/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.36Ctt6sTruef.png b/data/CLs/plots/bplus_0/0.36Ctt6sTruef.png index d2dbe59..ff026dc 100644 --- a/data/CLs/plots/bplus_0/0.36Ctt6sTruef.png +++ b/data/CLs/plots/bplus_0/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.36Ctt7sFalsef.png b/data/CLs/plots/bplus_0/0.36Ctt7sFalsef.png index af054f5..93f12d8 100644 --- a/data/CLs/plots/bplus_0/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/bplus_0/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.41Ctt8sTruef.png b/data/CLs/plots/bplus_0/0.41Ctt8sTruef.png index 07f7d28..e4a7651 100644 --- a/data/CLs/plots/bplus_0/0.41Ctt8sTruef.png +++ b/data/CLs/plots/bplus_0/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.41Ctt9sFalsef.png b/data/CLs/plots/bplus_0/0.41Ctt9sFalsef.png index 4c6f7e2..4dbbe75 100644 --- a/data/CLs/plots/bplus_0/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/bplus_0/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.45Ctt10sTruef.png b/data/CLs/plots/bplus_0/0.45Ctt10sTruef.png index 6301220..8b08a91 100644 --- a/data/CLs/plots/bplus_0/0.45Ctt10sTruef.png +++ b/data/CLs/plots/bplus_0/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.45Ctt11sFalsef.png b/data/CLs/plots/bplus_0/0.45Ctt11sFalsef.png index 21699b1..999ae01 100644 --- a/data/CLs/plots/bplus_0/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/bplus_0/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.49Ctt12sTruef.png b/data/CLs/plots/bplus_0/0.49Ctt12sTruef.png index f7f23d9..08b3224 100644 --- a/data/CLs/plots/bplus_0/0.49Ctt12sTruef.png +++ b/data/CLs/plots/bplus_0/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.49Ctt13sFalsef.png b/data/CLs/plots/bplus_0/0.49Ctt13sFalsef.png index b0ba3f1..2b720fc 100644 --- a/data/CLs/plots/bplus_0/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/bplus_0/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.53Ctt14sTruef.png b/data/CLs/plots/bplus_0/0.53Ctt14sTruef.png index 510fe7f..6ab94f1 100644 --- a/data/CLs/plots/bplus_0/0.53Ctt14sTruef.png +++ b/data/CLs/plots/bplus_0/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.53Ctt15sFalsef.png b/data/CLs/plots/bplus_0/0.53Ctt15sFalsef.png index b8f2445..447703b 100644 --- a/data/CLs/plots/bplus_0/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/bplus_0/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.56Ctt16sTruef.png b/data/CLs/plots/bplus_0/0.56Ctt16sTruef.png index 9970943..983d391 100644 --- a/data/CLs/plots/bplus_0/0.56Ctt16sTruef.png +++ b/data/CLs/plots/bplus_0/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.56Ctt17sFalsef.png b/data/CLs/plots/bplus_0/0.56Ctt17sFalsef.png index 8b59512..491ebe0 100644 --- a/data/CLs/plots/bplus_0/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/bplus_0/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.59Ctt18sTruef.png b/data/CLs/plots/bplus_0/0.59Ctt18sTruef.png index 68040bd..0eae552 100644 --- a/data/CLs/plots/bplus_0/0.59Ctt18sTruef.png +++ b/data/CLs/plots/bplus_0/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.59Ctt19sFalsef.png b/data/CLs/plots/bplus_0/0.59Ctt19sFalsef.png index f0ee106..4cf64ec 100644 --- a/data/CLs/plots/bplus_0/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/bplus_0/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.62Ctt20sTruef.png b/data/CLs/plots/bplus_0/0.62Ctt20sTruef.png index b59a3fe..cef7961 100644 --- a/data/CLs/plots/bplus_0/0.62Ctt20sTruef.png +++ b/data/CLs/plots/bplus_0/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.62Ctt21sFalsef.png b/data/CLs/plots/bplus_0/0.62Ctt21sFalsef.png index 6af1961..ae9902d 100644 --- a/data/CLs/plots/bplus_0/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/bplus_0/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.65Ctt22sTruef.png b/data/CLs/plots/bplus_0/0.65Ctt22sTruef.png index a750065..2d0d48a 100644 --- a/data/CLs/plots/bplus_0/0.65Ctt22sTruef.png +++ b/data/CLs/plots/bplus_0/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.65Ctt23sFalsef.png b/data/CLs/plots/bplus_0/0.65Ctt23sFalsef.png index 375f4cb..bb546e3 100644 --- a/data/CLs/plots/bplus_0/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/bplus_0/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.68Ctt24sTruef.png b/data/CLs/plots/bplus_0/0.68Ctt24sTruef.png index da9300e..b1a0628 100644 --- a/data/CLs/plots/bplus_0/0.68Ctt24sTruef.png +++ b/data/CLs/plots/bplus_0/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.68Ctt25sFalsef.png b/data/CLs/plots/bplus_0/0.68Ctt25sFalsef.png index d7508c4..dca78be 100644 --- a/data/CLs/plots/bplus_0/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/bplus_0/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.70Ctt26sTruef.png b/data/CLs/plots/bplus_0/0.70Ctt26sTruef.png index 1adf78b..6573ef5 100644 --- a/data/CLs/plots/bplus_0/0.70Ctt26sTruef.png +++ b/data/CLs/plots/bplus_0/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.70Ctt27sFalsef.png b/data/CLs/plots/bplus_0/0.70Ctt27sFalsef.png index 17d20e9..a97b9d0 100644 --- a/data/CLs/plots/bplus_0/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/bplus_0/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.73Ctt28sTruef.png b/data/CLs/plots/bplus_0/0.73Ctt28sTruef.png index 2228b9e..b312826 100644 --- a/data/CLs/plots/bplus_0/0.73Ctt28sTruef.png +++ b/data/CLs/plots/bplus_0/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.73Ctt29sFalsef.png b/data/CLs/plots/bplus_0/0.73Ctt29sFalsef.png index c8ab8ea..3365c12 100644 --- a/data/CLs/plots/bplus_0/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/bplus_0/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.75Ctt30sTruef.png b/data/CLs/plots/bplus_0/0.75Ctt30sTruef.png index 1bc3e09..6106f57 100644 --- a/data/CLs/plots/bplus_0/0.75Ctt30sTruef.png +++ b/data/CLs/plots/bplus_0/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.75Ctt31sFalsef.png b/data/CLs/plots/bplus_0/0.75Ctt31sFalsef.png index fa1427c..3348f30 100644 --- a/data/CLs/plots/bplus_0/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/bplus_0/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.78Ctt32sTruef.png b/data/CLs/plots/bplus_0/0.78Ctt32sTruef.png index a5696ae..1ef5094 100644 --- a/data/CLs/plots/bplus_0/0.78Ctt32sTruef.png +++ b/data/CLs/plots/bplus_0/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.78Ctt33sFalsef.png b/data/CLs/plots/bplus_0/0.78Ctt33sFalsef.png index 3dc323d..14782df 100644 --- a/data/CLs/plots/bplus_0/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/bplus_0/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.80Ctt34sTruef.png b/data/CLs/plots/bplus_0/0.80Ctt34sTruef.png index 61e4ef8..1464204 100644 --- a/data/CLs/plots/bplus_0/0.80Ctt34sTruef.png +++ b/data/CLs/plots/bplus_0/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.80Ctt35sFalsef.png b/data/CLs/plots/bplus_0/0.80Ctt35sFalsef.png index 2d470e1..25fc1d3 100644 --- a/data/CLs/plots/bplus_0/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/bplus_0/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.82Ctt36sTruef.png b/data/CLs/plots/bplus_0/0.82Ctt36sTruef.png index 53d00e0..284a406 100644 --- a/data/CLs/plots/bplus_0/0.82Ctt36sTruef.png +++ b/data/CLs/plots/bplus_0/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.82Ctt37sFalsef.png b/data/CLs/plots/bplus_0/0.82Ctt37sFalsef.png index 3d0ef2d..305ff54 100644 --- a/data/CLs/plots/bplus_0/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/bplus_0/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.85Ctt38sTruef.png b/data/CLs/plots/bplus_0/0.85Ctt38sTruef.png index 7637075..b6c5eb6 100644 --- a/data/CLs/plots/bplus_0/0.85Ctt38sTruef.png +++ b/data/CLs/plots/bplus_0/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_0/0.85Ctt39sFalsef.png b/data/CLs/plots/bplus_0/0.85Ctt39sFalsef.png index adf0027..8618510 100644 --- a/data/CLs/plots/bplus_0/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/bplus_0/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.00Ctt0sTruef.png b/data/CLs/plots/bplus_1/0.00Ctt0sTruef.png index a4647a1..9a4762a 100644 --- a/data/CLs/plots/bplus_1/0.00Ctt0sTruef.png +++ b/data/CLs/plots/bplus_1/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.00Ctt1sFalsef.png b/data/CLs/plots/bplus_1/0.00Ctt1sFalsef.png index 9a19417..68c872e 100644 --- a/data/CLs/plots/bplus_1/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/bplus_1/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.25Ctt2sTruef.png b/data/CLs/plots/bplus_1/0.25Ctt2sTruef.png index 9c12bff..30ed85c 100644 --- a/data/CLs/plots/bplus_1/0.25Ctt2sTruef.png +++ b/data/CLs/plots/bplus_1/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.25Ctt3sFalsef.png b/data/CLs/plots/bplus_1/0.25Ctt3sFalsef.png index 9f80932..bdada97 100644 --- a/data/CLs/plots/bplus_1/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/bplus_1/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.31Ctt4sTruef.png b/data/CLs/plots/bplus_1/0.31Ctt4sTruef.png index b6a1c96..cbdc73e 100644 --- a/data/CLs/plots/bplus_1/0.31Ctt4sTruef.png +++ b/data/CLs/plots/bplus_1/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.31Ctt5sFalsef.png b/data/CLs/plots/bplus_1/0.31Ctt5sFalsef.png index 04c65bf..e464bff 100644 --- a/data/CLs/plots/bplus_1/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/bplus_1/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.36Ctt6sTruef.png b/data/CLs/plots/bplus_1/0.36Ctt6sTruef.png index a424185..b465cd6 100644 --- a/data/CLs/plots/bplus_1/0.36Ctt6sTruef.png +++ b/data/CLs/plots/bplus_1/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.36Ctt7sFalsef.png b/data/CLs/plots/bplus_1/0.36Ctt7sFalsef.png index 9e895ec..848fb69 100644 --- a/data/CLs/plots/bplus_1/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/bplus_1/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.41Ctt8sTruef.png b/data/CLs/plots/bplus_1/0.41Ctt8sTruef.png index 3b30672..d9e5d3d 100644 --- a/data/CLs/plots/bplus_1/0.41Ctt8sTruef.png +++ b/data/CLs/plots/bplus_1/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.41Ctt9sFalsef.png b/data/CLs/plots/bplus_1/0.41Ctt9sFalsef.png index 8d8bd94..02c1374 100644 --- a/data/CLs/plots/bplus_1/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/bplus_1/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.45Ctt10sTruef.png b/data/CLs/plots/bplus_1/0.45Ctt10sTruef.png index d731c1b..85188e1 100644 --- a/data/CLs/plots/bplus_1/0.45Ctt10sTruef.png +++ b/data/CLs/plots/bplus_1/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.45Ctt11sFalsef.png b/data/CLs/plots/bplus_1/0.45Ctt11sFalsef.png index 69b8e8f..b67761b 100644 --- a/data/CLs/plots/bplus_1/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/bplus_1/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.49Ctt12sTruef.png b/data/CLs/plots/bplus_1/0.49Ctt12sTruef.png index 1a2480d..ce82eeb 100644 --- a/data/CLs/plots/bplus_1/0.49Ctt12sTruef.png +++ b/data/CLs/plots/bplus_1/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.49Ctt13sFalsef.png b/data/CLs/plots/bplus_1/0.49Ctt13sFalsef.png index e383c11..75adce8 100644 --- a/data/CLs/plots/bplus_1/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/bplus_1/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.53Ctt14sTruef.png b/data/CLs/plots/bplus_1/0.53Ctt14sTruef.png index ad54072..edbfcb8 100644 --- a/data/CLs/plots/bplus_1/0.53Ctt14sTruef.png +++ b/data/CLs/plots/bplus_1/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.53Ctt15sFalsef.png b/data/CLs/plots/bplus_1/0.53Ctt15sFalsef.png index 7dc11e6..2669d83 100644 --- a/data/CLs/plots/bplus_1/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/bplus_1/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.56Ctt16sTruef.png b/data/CLs/plots/bplus_1/0.56Ctt16sTruef.png index f871aa1..bd02061 100644 --- a/data/CLs/plots/bplus_1/0.56Ctt16sTruef.png +++ b/data/CLs/plots/bplus_1/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.56Ctt17sFalsef.png b/data/CLs/plots/bplus_1/0.56Ctt17sFalsef.png index 8382c83..59958d1 100644 --- a/data/CLs/plots/bplus_1/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/bplus_1/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.59Ctt18sTruef.png b/data/CLs/plots/bplus_1/0.59Ctt18sTruef.png index e82d7e6..d4074fc 100644 --- a/data/CLs/plots/bplus_1/0.59Ctt18sTruef.png +++ b/data/CLs/plots/bplus_1/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.59Ctt19sFalsef.png b/data/CLs/plots/bplus_1/0.59Ctt19sFalsef.png index e2e8cbf..3916a2c 100644 --- a/data/CLs/plots/bplus_1/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/bplus_1/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.62Ctt20sTruef.png b/data/CLs/plots/bplus_1/0.62Ctt20sTruef.png index 0e2aad7..83f6415 100644 --- a/data/CLs/plots/bplus_1/0.62Ctt20sTruef.png +++ b/data/CLs/plots/bplus_1/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.62Ctt21sFalsef.png b/data/CLs/plots/bplus_1/0.62Ctt21sFalsef.png index ded4c2e..ff4ef29 100644 --- a/data/CLs/plots/bplus_1/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/bplus_1/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.65Ctt22sTruef.png b/data/CLs/plots/bplus_1/0.65Ctt22sTruef.png index d2d6916..25abab0 100644 --- a/data/CLs/plots/bplus_1/0.65Ctt22sTruef.png +++ b/data/CLs/plots/bplus_1/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.65Ctt23sFalsef.png b/data/CLs/plots/bplus_1/0.65Ctt23sFalsef.png index ec808b1..c540afd 100644 --- a/data/CLs/plots/bplus_1/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/bplus_1/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.68Ctt24sTruef.png b/data/CLs/plots/bplus_1/0.68Ctt24sTruef.png index c640a6e..33a518f 100644 --- a/data/CLs/plots/bplus_1/0.68Ctt24sTruef.png +++ b/data/CLs/plots/bplus_1/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.68Ctt25sFalsef.png b/data/CLs/plots/bplus_1/0.68Ctt25sFalsef.png index 0e68d43..b7a3d2a 100644 --- a/data/CLs/plots/bplus_1/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/bplus_1/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.70Ctt26sTruef.png b/data/CLs/plots/bplus_1/0.70Ctt26sTruef.png index 2af3bd1..413d03f 100644 --- a/data/CLs/plots/bplus_1/0.70Ctt26sTruef.png +++ b/data/CLs/plots/bplus_1/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.70Ctt27sFalsef.png b/data/CLs/plots/bplus_1/0.70Ctt27sFalsef.png index 02e5227..b6605c7 100644 --- a/data/CLs/plots/bplus_1/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/bplus_1/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.73Ctt28sTruef.png b/data/CLs/plots/bplus_1/0.73Ctt28sTruef.png index b957a70..5da6871 100644 --- a/data/CLs/plots/bplus_1/0.73Ctt28sTruef.png +++ b/data/CLs/plots/bplus_1/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.73Ctt29sFalsef.png b/data/CLs/plots/bplus_1/0.73Ctt29sFalsef.png index 7fa72cc..9a075a9 100644 --- a/data/CLs/plots/bplus_1/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/bplus_1/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.75Ctt30sTruef.png b/data/CLs/plots/bplus_1/0.75Ctt30sTruef.png index 08aa765..e611fdd 100644 --- a/data/CLs/plots/bplus_1/0.75Ctt30sTruef.png +++ b/data/CLs/plots/bplus_1/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.75Ctt31sFalsef.png b/data/CLs/plots/bplus_1/0.75Ctt31sFalsef.png index 13fd3ec..9630c2e 100644 --- a/data/CLs/plots/bplus_1/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/bplus_1/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.78Ctt32sTruef.png b/data/CLs/plots/bplus_1/0.78Ctt32sTruef.png index f2f1b82..29be528 100644 --- a/data/CLs/plots/bplus_1/0.78Ctt32sTruef.png +++ b/data/CLs/plots/bplus_1/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.78Ctt33sFalsef.png b/data/CLs/plots/bplus_1/0.78Ctt33sFalsef.png index 0b7b2f0..7329af3 100644 --- a/data/CLs/plots/bplus_1/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/bplus_1/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.80Ctt34sTruef.png b/data/CLs/plots/bplus_1/0.80Ctt34sTruef.png index cfb32cf..5d13466 100644 --- a/data/CLs/plots/bplus_1/0.80Ctt34sTruef.png +++ b/data/CLs/plots/bplus_1/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.80Ctt35sFalsef.png b/data/CLs/plots/bplus_1/0.80Ctt35sFalsef.png index 95659ec..28fb6c0 100644 --- a/data/CLs/plots/bplus_1/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/bplus_1/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.82Ctt36sTruef.png b/data/CLs/plots/bplus_1/0.82Ctt36sTruef.png index 00bbde9..a6d461e 100644 --- a/data/CLs/plots/bplus_1/0.82Ctt36sTruef.png +++ b/data/CLs/plots/bplus_1/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.82Ctt37sFalsef.png b/data/CLs/plots/bplus_1/0.82Ctt37sFalsef.png index ac111cf..f20c901 100644 --- a/data/CLs/plots/bplus_1/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/bplus_1/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.85Ctt38sTruef.png b/data/CLs/plots/bplus_1/0.85Ctt38sTruef.png index f7c44da..b531eda 100644 --- a/data/CLs/plots/bplus_1/0.85Ctt38sTruef.png +++ b/data/CLs/plots/bplus_1/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_1/0.85Ctt39sFalsef.png b/data/CLs/plots/bplus_1/0.85Ctt39sFalsef.png index 5bb6c66..eecf1c1 100644 --- a/data/CLs/plots/bplus_1/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/bplus_1/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.00Ctt0sTruef.png b/data/CLs/plots/bplus_2/0.00Ctt0sTruef.png index e658258..ab7236b 100644 --- a/data/CLs/plots/bplus_2/0.00Ctt0sTruef.png +++ b/data/CLs/plots/bplus_2/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.00Ctt1sFalsef.png b/data/CLs/plots/bplus_2/0.00Ctt1sFalsef.png index 5cc79ce..3f0fbae 100644 --- a/data/CLs/plots/bplus_2/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/bplus_2/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.25Ctt2sTruef.png b/data/CLs/plots/bplus_2/0.25Ctt2sTruef.png index ece291d..e508c06 100644 --- a/data/CLs/plots/bplus_2/0.25Ctt2sTruef.png +++ b/data/CLs/plots/bplus_2/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.25Ctt3sFalsef.png b/data/CLs/plots/bplus_2/0.25Ctt3sFalsef.png index 58105d1..c461a52 100644 --- a/data/CLs/plots/bplus_2/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/bplus_2/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.31Ctt4sTruef.png b/data/CLs/plots/bplus_2/0.31Ctt4sTruef.png index f4fb14a..e17e163 100644 --- a/data/CLs/plots/bplus_2/0.31Ctt4sTruef.png +++ b/data/CLs/plots/bplus_2/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.31Ctt5sFalsef.png b/data/CLs/plots/bplus_2/0.31Ctt5sFalsef.png index c6ac35c..1e419de 100644 --- a/data/CLs/plots/bplus_2/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/bplus_2/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.36Ctt6sTruef.png b/data/CLs/plots/bplus_2/0.36Ctt6sTruef.png index cfc8a5d..dea8292 100644 --- a/data/CLs/plots/bplus_2/0.36Ctt6sTruef.png +++ b/data/CLs/plots/bplus_2/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.36Ctt7sFalsef.png b/data/CLs/plots/bplus_2/0.36Ctt7sFalsef.png index 3badc32..1a568fc 100644 --- a/data/CLs/plots/bplus_2/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/bplus_2/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.41Ctt8sTruef.png b/data/CLs/plots/bplus_2/0.41Ctt8sTruef.png index 07bd555..1502715 100644 --- a/data/CLs/plots/bplus_2/0.41Ctt8sTruef.png +++ b/data/CLs/plots/bplus_2/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.41Ctt9sFalsef.png b/data/CLs/plots/bplus_2/0.41Ctt9sFalsef.png index fb1970c..45c8d78 100644 --- a/data/CLs/plots/bplus_2/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/bplus_2/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.45Ctt10sTruef.png b/data/CLs/plots/bplus_2/0.45Ctt10sTruef.png index 595fe26..bcbb085 100644 --- a/data/CLs/plots/bplus_2/0.45Ctt10sTruef.png +++ b/data/CLs/plots/bplus_2/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.45Ctt11sFalsef.png b/data/CLs/plots/bplus_2/0.45Ctt11sFalsef.png index af2eab5..78e3b32 100644 --- a/data/CLs/plots/bplus_2/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/bplus_2/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.49Ctt12sTruef.png b/data/CLs/plots/bplus_2/0.49Ctt12sTruef.png index 99ae865..0614337 100644 --- a/data/CLs/plots/bplus_2/0.49Ctt12sTruef.png +++ b/data/CLs/plots/bplus_2/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.49Ctt13sFalsef.png b/data/CLs/plots/bplus_2/0.49Ctt13sFalsef.png index 25d3483..624f677 100644 --- a/data/CLs/plots/bplus_2/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/bplus_2/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.53Ctt14sTruef.png b/data/CLs/plots/bplus_2/0.53Ctt14sTruef.png index 60c6173..af482b9 100644 --- a/data/CLs/plots/bplus_2/0.53Ctt14sTruef.png +++ b/data/CLs/plots/bplus_2/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.53Ctt15sFalsef.png b/data/CLs/plots/bplus_2/0.53Ctt15sFalsef.png index ac1024c..49a03aa 100644 --- a/data/CLs/plots/bplus_2/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/bplus_2/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.56Ctt16sTruef.png b/data/CLs/plots/bplus_2/0.56Ctt16sTruef.png index 5e13f49..d85e693 100644 --- a/data/CLs/plots/bplus_2/0.56Ctt16sTruef.png +++ b/data/CLs/plots/bplus_2/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.56Ctt17sFalsef.png b/data/CLs/plots/bplus_2/0.56Ctt17sFalsef.png index c47f749..2f06f0f 100644 --- a/data/CLs/plots/bplus_2/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/bplus_2/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.59Ctt18sTruef.png b/data/CLs/plots/bplus_2/0.59Ctt18sTruef.png index a22e2c5..6bfa609 100644 --- a/data/CLs/plots/bplus_2/0.59Ctt18sTruef.png +++ b/data/CLs/plots/bplus_2/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.59Ctt19sFalsef.png b/data/CLs/plots/bplus_2/0.59Ctt19sFalsef.png index 5234d10..4519e13 100644 --- a/data/CLs/plots/bplus_2/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/bplus_2/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.62Ctt20sTruef.png b/data/CLs/plots/bplus_2/0.62Ctt20sTruef.png index a5388ea..fd4f6df 100644 --- a/data/CLs/plots/bplus_2/0.62Ctt20sTruef.png +++ b/data/CLs/plots/bplus_2/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.62Ctt21sFalsef.png b/data/CLs/plots/bplus_2/0.62Ctt21sFalsef.png index 1327798..eff2403 100644 --- a/data/CLs/plots/bplus_2/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/bplus_2/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.65Ctt22sTruef.png b/data/CLs/plots/bplus_2/0.65Ctt22sTruef.png index 18ddc92..e9e82a5 100644 --- a/data/CLs/plots/bplus_2/0.65Ctt22sTruef.png +++ b/data/CLs/plots/bplus_2/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.65Ctt23sFalsef.png b/data/CLs/plots/bplus_2/0.65Ctt23sFalsef.png index 7c72e6e..cd790c5 100644 --- a/data/CLs/plots/bplus_2/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/bplus_2/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.68Ctt24sTruef.png b/data/CLs/plots/bplus_2/0.68Ctt24sTruef.png index 6828ef8..984dc3e 100644 --- a/data/CLs/plots/bplus_2/0.68Ctt24sTruef.png +++ b/data/CLs/plots/bplus_2/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.68Ctt25sFalsef.png b/data/CLs/plots/bplus_2/0.68Ctt25sFalsef.png index 7f477c7..3e50c6c 100644 --- a/data/CLs/plots/bplus_2/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/bplus_2/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.70Ctt26sTruef.png b/data/CLs/plots/bplus_2/0.70Ctt26sTruef.png index 6582bc7..97241dc 100644 --- a/data/CLs/plots/bplus_2/0.70Ctt26sTruef.png +++ b/data/CLs/plots/bplus_2/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.70Ctt27sFalsef.png b/data/CLs/plots/bplus_2/0.70Ctt27sFalsef.png index b0e8b78..83aed24 100644 --- a/data/CLs/plots/bplus_2/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/bplus_2/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.73Ctt28sTruef.png b/data/CLs/plots/bplus_2/0.73Ctt28sTruef.png index 64a0572..9adeb78 100644 --- a/data/CLs/plots/bplus_2/0.73Ctt28sTruef.png +++ b/data/CLs/plots/bplus_2/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.73Ctt29sFalsef.png b/data/CLs/plots/bplus_2/0.73Ctt29sFalsef.png index 13baa84..5c3af2e 100644 --- a/data/CLs/plots/bplus_2/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/bplus_2/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.75Ctt30sTruef.png b/data/CLs/plots/bplus_2/0.75Ctt30sTruef.png index ed6d970..63a3b6a 100644 --- a/data/CLs/plots/bplus_2/0.75Ctt30sTruef.png +++ b/data/CLs/plots/bplus_2/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.75Ctt31sFalsef.png b/data/CLs/plots/bplus_2/0.75Ctt31sFalsef.png index 66eb0f9..1b9838c 100644 --- a/data/CLs/plots/bplus_2/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/bplus_2/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.78Ctt32sTruef.png b/data/CLs/plots/bplus_2/0.78Ctt32sTruef.png index e326bed..a0de1fa 100644 --- a/data/CLs/plots/bplus_2/0.78Ctt32sTruef.png +++ b/data/CLs/plots/bplus_2/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.78Ctt33sFalsef.png b/data/CLs/plots/bplus_2/0.78Ctt33sFalsef.png index 8bede2c..2e250db 100644 --- a/data/CLs/plots/bplus_2/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/bplus_2/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.80Ctt34sTruef.png b/data/CLs/plots/bplus_2/0.80Ctt34sTruef.png index a8a4c88..ad8b0ff 100644 --- a/data/CLs/plots/bplus_2/0.80Ctt34sTruef.png +++ b/data/CLs/plots/bplus_2/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.80Ctt35sFalsef.png b/data/CLs/plots/bplus_2/0.80Ctt35sFalsef.png index 5e1633a..475e158 100644 --- a/data/CLs/plots/bplus_2/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/bplus_2/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.82Ctt36sTruef.png b/data/CLs/plots/bplus_2/0.82Ctt36sTruef.png index 4959c18..782683a 100644 --- a/data/CLs/plots/bplus_2/0.82Ctt36sTruef.png +++ b/data/CLs/plots/bplus_2/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.82Ctt37sFalsef.png b/data/CLs/plots/bplus_2/0.82Ctt37sFalsef.png index 5d4ea48..7c96d49 100644 --- a/data/CLs/plots/bplus_2/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/bplus_2/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.85Ctt38sTruef.png b/data/CLs/plots/bplus_2/0.85Ctt38sTruef.png index 6eb5dca..c1a9d2b 100644 --- a/data/CLs/plots/bplus_2/0.85Ctt38sTruef.png +++ b/data/CLs/plots/bplus_2/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/bplus_2/0.85Ctt39sFalsef.png b/data/CLs/plots/bplus_2/0.85Ctt39sFalsef.png index 1fdaa2a..1b9fecc 100644 --- a/data/CLs/plots/bplus_2/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/bplus_2/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.00Ctt0sTruef.png b/data/CLs/plots/jpsi_p/0.00Ctt0sTruef.png index b0c28e7..c68f718 100644 --- a/data/CLs/plots/jpsi_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/jpsi_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.00Ctt1sFalsef.png b/data/CLs/plots/jpsi_p/0.00Ctt1sFalsef.png index 9e1b976..22b4d9d 100644 --- a/data/CLs/plots/jpsi_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.25Ctt2sTruef.png b/data/CLs/plots/jpsi_p/0.25Ctt2sTruef.png index 420f65b..4e90c4b 100644 --- a/data/CLs/plots/jpsi_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/jpsi_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.25Ctt3sFalsef.png b/data/CLs/plots/jpsi_p/0.25Ctt3sFalsef.png index 674438f..1215fb0 100644 --- a/data/CLs/plots/jpsi_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.31Ctt4sTruef.png b/data/CLs/plots/jpsi_p/0.31Ctt4sTruef.png index 04ce02f..467a031 100644 --- a/data/CLs/plots/jpsi_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/jpsi_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.31Ctt5sFalsef.png b/data/CLs/plots/jpsi_p/0.31Ctt5sFalsef.png index e54367a..18d9cc8 100644 --- a/data/CLs/plots/jpsi_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.36Ctt6sTruef.png b/data/CLs/plots/jpsi_p/0.36Ctt6sTruef.png index 25e9d2b..efb53f3 100644 --- a/data/CLs/plots/jpsi_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/jpsi_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.36Ctt7sFalsef.png b/data/CLs/plots/jpsi_p/0.36Ctt7sFalsef.png index b294eb8..39d31cf 100644 --- a/data/CLs/plots/jpsi_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.41Ctt8sTruef.png b/data/CLs/plots/jpsi_p/0.41Ctt8sTruef.png index 07d86ae..9df719d 100644 --- a/data/CLs/plots/jpsi_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/jpsi_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.41Ctt9sFalsef.png b/data/CLs/plots/jpsi_p/0.41Ctt9sFalsef.png index ce7ae08..12c70b4 100644 --- a/data/CLs/plots/jpsi_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.45Ctt10sTruef.png b/data/CLs/plots/jpsi_p/0.45Ctt10sTruef.png index b6b9f61..38c03ca 100644 --- a/data/CLs/plots/jpsi_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/jpsi_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.45Ctt11sFalsef.png b/data/CLs/plots/jpsi_p/0.45Ctt11sFalsef.png index 5ec7de4..d200ca0 100644 --- a/data/CLs/plots/jpsi_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.49Ctt12sTruef.png b/data/CLs/plots/jpsi_p/0.49Ctt12sTruef.png index d7b9e75..47fb6e6 100644 --- a/data/CLs/plots/jpsi_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/jpsi_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.49Ctt13sFalsef.png b/data/CLs/plots/jpsi_p/0.49Ctt13sFalsef.png index f491f16..2a888e6 100644 --- a/data/CLs/plots/jpsi_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.53Ctt14sTruef.png b/data/CLs/plots/jpsi_p/0.53Ctt14sTruef.png index bd9c5ae..faa4495 100644 --- a/data/CLs/plots/jpsi_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/jpsi_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.53Ctt15sFalsef.png b/data/CLs/plots/jpsi_p/0.53Ctt15sFalsef.png index 8665ada..1e46a35 100644 --- a/data/CLs/plots/jpsi_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.56Ctt16sTruef.png b/data/CLs/plots/jpsi_p/0.56Ctt16sTruef.png index 25eb754..b639972 100644 --- a/data/CLs/plots/jpsi_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/jpsi_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.56Ctt17sFalsef.png b/data/CLs/plots/jpsi_p/0.56Ctt17sFalsef.png index 2969a4b..1f8666d 100644 --- a/data/CLs/plots/jpsi_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.59Ctt18sTruef.png b/data/CLs/plots/jpsi_p/0.59Ctt18sTruef.png index 7af55f8..341ed8f 100644 --- a/data/CLs/plots/jpsi_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/jpsi_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.59Ctt19sFalsef.png b/data/CLs/plots/jpsi_p/0.59Ctt19sFalsef.png index 3cf6795..d247878 100644 --- a/data/CLs/plots/jpsi_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.62Ctt20sTruef.png b/data/CLs/plots/jpsi_p/0.62Ctt20sTruef.png index cfac1ab..a4f30c5 100644 --- a/data/CLs/plots/jpsi_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/jpsi_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.62Ctt21sFalsef.png b/data/CLs/plots/jpsi_p/0.62Ctt21sFalsef.png index e40df61..c829e84 100644 --- a/data/CLs/plots/jpsi_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.65Ctt22sTruef.png b/data/CLs/plots/jpsi_p/0.65Ctt22sTruef.png index b66cc26..a1056ff 100644 --- a/data/CLs/plots/jpsi_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/jpsi_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.65Ctt23sFalsef.png b/data/CLs/plots/jpsi_p/0.65Ctt23sFalsef.png index 95ab3c8..d238d3a 100644 --- a/data/CLs/plots/jpsi_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.68Ctt24sTruef.png b/data/CLs/plots/jpsi_p/0.68Ctt24sTruef.png index 6afd4dd..b57ddc3 100644 --- a/data/CLs/plots/jpsi_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/jpsi_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.68Ctt25sFalsef.png b/data/CLs/plots/jpsi_p/0.68Ctt25sFalsef.png index 7e6de5a..c49c4de 100644 --- a/data/CLs/plots/jpsi_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.70Ctt26sTruef.png b/data/CLs/plots/jpsi_p/0.70Ctt26sTruef.png index 70ad413..8ab401d 100644 --- a/data/CLs/plots/jpsi_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/jpsi_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.70Ctt27sFalsef.png b/data/CLs/plots/jpsi_p/0.70Ctt27sFalsef.png index 3f6bcac..6dfc7ff 100644 --- a/data/CLs/plots/jpsi_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.73Ctt28sTruef.png b/data/CLs/plots/jpsi_p/0.73Ctt28sTruef.png index 0546e1d..bd5b01d 100644 --- a/data/CLs/plots/jpsi_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/jpsi_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.73Ctt29sFalsef.png b/data/CLs/plots/jpsi_p/0.73Ctt29sFalsef.png index bde9bb0..dc2c27b 100644 --- a/data/CLs/plots/jpsi_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.75Ctt30sTruef.png b/data/CLs/plots/jpsi_p/0.75Ctt30sTruef.png index 9fcbe7d..19e0569 100644 --- a/data/CLs/plots/jpsi_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/jpsi_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.75Ctt31sFalsef.png b/data/CLs/plots/jpsi_p/0.75Ctt31sFalsef.png index 04e2630..e960d62 100644 --- a/data/CLs/plots/jpsi_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.78Ctt32sTruef.png b/data/CLs/plots/jpsi_p/0.78Ctt32sTruef.png index 7930bd1..1f60662 100644 --- a/data/CLs/plots/jpsi_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/jpsi_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.78Ctt33sFalsef.png b/data/CLs/plots/jpsi_p/0.78Ctt33sFalsef.png index 6f45ff2..1042e89 100644 --- a/data/CLs/plots/jpsi_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.80Ctt34sTruef.png b/data/CLs/plots/jpsi_p/0.80Ctt34sTruef.png index 7944275..21b83ba 100644 --- a/data/CLs/plots/jpsi_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/jpsi_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.80Ctt35sFalsef.png b/data/CLs/plots/jpsi_p/0.80Ctt35sFalsef.png index 581602f..7849b28 100644 --- a/data/CLs/plots/jpsi_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.82Ctt36sTruef.png b/data/CLs/plots/jpsi_p/0.82Ctt36sTruef.png index 2a34a79..ae33397 100644 --- a/data/CLs/plots/jpsi_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/jpsi_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.82Ctt37sFalsef.png b/data/CLs/plots/jpsi_p/0.82Ctt37sFalsef.png index c875872..f63f38e 100644 --- a/data/CLs/plots/jpsi_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.85Ctt38sTruef.png b/data/CLs/plots/jpsi_p/0.85Ctt38sTruef.png index 5530d06..d158043 100644 --- a/data/CLs/plots/jpsi_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/jpsi_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/jpsi_p/0.85Ctt39sFalsef.png b/data/CLs/plots/jpsi_p/0.85Ctt39sFalsef.png index 31add24..34c2814 100644 --- a/data/CLs/plots/jpsi_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/jpsi_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.00Ctt0sTruef.png b/data/CLs/plots/omega_p/0.00Ctt0sTruef.png index b5bf301..d85d327 100644 --- a/data/CLs/plots/omega_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/omega_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.00Ctt1sFalsef.png b/data/CLs/plots/omega_p/0.00Ctt1sFalsef.png index 746cd02..4a7f8b2 100644 --- a/data/CLs/plots/omega_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/omega_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.25Ctt2sTruef.png b/data/CLs/plots/omega_p/0.25Ctt2sTruef.png index ebae4d3..b9255ad 100644 --- a/data/CLs/plots/omega_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/omega_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.25Ctt3sFalsef.png b/data/CLs/plots/omega_p/0.25Ctt3sFalsef.png index 9aba5a6..866bb84 100644 --- a/data/CLs/plots/omega_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/omega_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.31Ctt4sTruef.png b/data/CLs/plots/omega_p/0.31Ctt4sTruef.png index 78d956f..d6fc26c 100644 --- a/data/CLs/plots/omega_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/omega_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.31Ctt5sFalsef.png b/data/CLs/plots/omega_p/0.31Ctt5sFalsef.png index d8ac45e..b60d965 100644 --- a/data/CLs/plots/omega_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/omega_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.36Ctt6sTruef.png b/data/CLs/plots/omega_p/0.36Ctt6sTruef.png index 24baf14..0b8e639 100644 --- a/data/CLs/plots/omega_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/omega_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.36Ctt7sFalsef.png b/data/CLs/plots/omega_p/0.36Ctt7sFalsef.png index 492c339..5e8fde3 100644 --- a/data/CLs/plots/omega_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/omega_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.41Ctt8sTruef.png b/data/CLs/plots/omega_p/0.41Ctt8sTruef.png index 6adb03d..600d986 100644 --- a/data/CLs/plots/omega_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/omega_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.41Ctt9sFalsef.png b/data/CLs/plots/omega_p/0.41Ctt9sFalsef.png index 08aa53e..9666b26 100644 --- a/data/CLs/plots/omega_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/omega_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.45Ctt10sTruef.png b/data/CLs/plots/omega_p/0.45Ctt10sTruef.png index c5efae0..f3f5570 100644 --- a/data/CLs/plots/omega_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/omega_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.45Ctt11sFalsef.png b/data/CLs/plots/omega_p/0.45Ctt11sFalsef.png index dabbe8d..b969846 100644 --- a/data/CLs/plots/omega_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/omega_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.49Ctt12sTruef.png b/data/CLs/plots/omega_p/0.49Ctt12sTruef.png index 84fa55d..c53c542 100644 --- a/data/CLs/plots/omega_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/omega_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.49Ctt13sFalsef.png b/data/CLs/plots/omega_p/0.49Ctt13sFalsef.png index bcb5350..92e446d 100644 --- a/data/CLs/plots/omega_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/omega_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.53Ctt14sTruef.png b/data/CLs/plots/omega_p/0.53Ctt14sTruef.png index c3e1c21..00dde0a 100644 --- a/data/CLs/plots/omega_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/omega_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.53Ctt15sFalsef.png b/data/CLs/plots/omega_p/0.53Ctt15sFalsef.png index de653c4..63e2828 100644 --- a/data/CLs/plots/omega_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/omega_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.56Ctt16sTruef.png b/data/CLs/plots/omega_p/0.56Ctt16sTruef.png index aaf4b93..094769d 100644 --- a/data/CLs/plots/omega_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/omega_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.56Ctt17sFalsef.png b/data/CLs/plots/omega_p/0.56Ctt17sFalsef.png index 9ab80d9..9101f81 100644 --- a/data/CLs/plots/omega_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/omega_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.59Ctt18sTruef.png b/data/CLs/plots/omega_p/0.59Ctt18sTruef.png index 1e2a9e1..1ca7942 100644 --- a/data/CLs/plots/omega_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/omega_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.59Ctt19sFalsef.png b/data/CLs/plots/omega_p/0.59Ctt19sFalsef.png index 4e51904..e58f22a 100644 --- a/data/CLs/plots/omega_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/omega_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.62Ctt20sTruef.png b/data/CLs/plots/omega_p/0.62Ctt20sTruef.png index 9fd65a4..617cf4b 100644 --- a/data/CLs/plots/omega_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/omega_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.62Ctt21sFalsef.png b/data/CLs/plots/omega_p/0.62Ctt21sFalsef.png index de3a2a7..b1274f9 100644 --- a/data/CLs/plots/omega_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/omega_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.65Ctt22sTruef.png b/data/CLs/plots/omega_p/0.65Ctt22sTruef.png index b5cddef..0c0f627 100644 --- a/data/CLs/plots/omega_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/omega_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.65Ctt23sFalsef.png b/data/CLs/plots/omega_p/0.65Ctt23sFalsef.png index efb2e32..1c25461 100644 --- a/data/CLs/plots/omega_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/omega_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.68Ctt24sTruef.png b/data/CLs/plots/omega_p/0.68Ctt24sTruef.png index d6e9ced..ce1358c 100644 --- a/data/CLs/plots/omega_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/omega_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.68Ctt25sFalsef.png b/data/CLs/plots/omega_p/0.68Ctt25sFalsef.png index 8003075..750fc31 100644 --- a/data/CLs/plots/omega_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/omega_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.70Ctt26sTruef.png b/data/CLs/plots/omega_p/0.70Ctt26sTruef.png index 20bd097..1a0845e 100644 --- a/data/CLs/plots/omega_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/omega_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.70Ctt27sFalsef.png b/data/CLs/plots/omega_p/0.70Ctt27sFalsef.png index 80012b4..2aa79aa 100644 --- a/data/CLs/plots/omega_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/omega_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.73Ctt28sTruef.png b/data/CLs/plots/omega_p/0.73Ctt28sTruef.png index 67065a1..9e52dff 100644 --- a/data/CLs/plots/omega_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/omega_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.73Ctt29sFalsef.png b/data/CLs/plots/omega_p/0.73Ctt29sFalsef.png index 1519a76..21fe4f9 100644 --- a/data/CLs/plots/omega_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/omega_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.75Ctt30sTruef.png b/data/CLs/plots/omega_p/0.75Ctt30sTruef.png index 6574ff4..eeb2867 100644 --- a/data/CLs/plots/omega_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/omega_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.75Ctt31sFalsef.png b/data/CLs/plots/omega_p/0.75Ctt31sFalsef.png index 976bb02..f3bc086 100644 --- a/data/CLs/plots/omega_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/omega_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.78Ctt32sTruef.png b/data/CLs/plots/omega_p/0.78Ctt32sTruef.png index af9595e..3f1f0e9 100644 --- a/data/CLs/plots/omega_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/omega_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.78Ctt33sFalsef.png b/data/CLs/plots/omega_p/0.78Ctt33sFalsef.png index 37e7a3c..07ade5b 100644 --- a/data/CLs/plots/omega_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/omega_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.80Ctt34sTruef.png b/data/CLs/plots/omega_p/0.80Ctt34sTruef.png index 14ae093..ab16fae 100644 --- a/data/CLs/plots/omega_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/omega_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.80Ctt35sFalsef.png b/data/CLs/plots/omega_p/0.80Ctt35sFalsef.png index 481fadc..3a3b01b 100644 --- a/data/CLs/plots/omega_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/omega_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.82Ctt36sTruef.png b/data/CLs/plots/omega_p/0.82Ctt36sTruef.png index 6a7f6cd..2038bae 100644 --- a/data/CLs/plots/omega_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/omega_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.82Ctt37sFalsef.png b/data/CLs/plots/omega_p/0.82Ctt37sFalsef.png index 9963bc9..2a3fba3 100644 --- a/data/CLs/plots/omega_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/omega_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.85Ctt38sTruef.png b/data/CLs/plots/omega_p/0.85Ctt38sTruef.png index a40e256..c3737e0 100644 --- a/data/CLs/plots/omega_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/omega_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_p/0.85Ctt39sFalsef.png b/data/CLs/plots/omega_p/0.85Ctt39sFalsef.png index 31e253b..b2a95d5 100644 --- a/data/CLs/plots/omega_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/omega_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.00Ctt0sTruef.png b/data/CLs/plots/omega_s/0.00Ctt0sTruef.png index b76a4fa..b280ef4 100644 --- a/data/CLs/plots/omega_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/omega_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.00Ctt1sFalsef.png b/data/CLs/plots/omega_s/0.00Ctt1sFalsef.png index e702e3e..ede203d 100644 --- a/data/CLs/plots/omega_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/omega_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.25Ctt2sTruef.png b/data/CLs/plots/omega_s/0.25Ctt2sTruef.png index 5078b6a..86eaa22 100644 --- a/data/CLs/plots/omega_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/omega_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.25Ctt3sFalsef.png b/data/CLs/plots/omega_s/0.25Ctt3sFalsef.png index fb37b56..7c6982e 100644 --- a/data/CLs/plots/omega_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/omega_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.31Ctt4sTruef.png b/data/CLs/plots/omega_s/0.31Ctt4sTruef.png index d628d8f..783dda0 100644 --- a/data/CLs/plots/omega_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/omega_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.31Ctt5sFalsef.png b/data/CLs/plots/omega_s/0.31Ctt5sFalsef.png index 61b149f..3e838e5 100644 --- a/data/CLs/plots/omega_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/omega_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.36Ctt6sTruef.png b/data/CLs/plots/omega_s/0.36Ctt6sTruef.png index 9bf338d..ab79f57 100644 --- a/data/CLs/plots/omega_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/omega_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.36Ctt7sFalsef.png b/data/CLs/plots/omega_s/0.36Ctt7sFalsef.png index e4f2adb..5dc3b67 100644 --- a/data/CLs/plots/omega_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/omega_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.41Ctt8sTruef.png b/data/CLs/plots/omega_s/0.41Ctt8sTruef.png index e9b1323..fb9ee1e 100644 --- a/data/CLs/plots/omega_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/omega_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.41Ctt9sFalsef.png b/data/CLs/plots/omega_s/0.41Ctt9sFalsef.png index 3ade217..a998cf6 100644 --- a/data/CLs/plots/omega_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/omega_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.45Ctt10sTruef.png b/data/CLs/plots/omega_s/0.45Ctt10sTruef.png index 61a0a55..1bcac27 100644 --- a/data/CLs/plots/omega_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/omega_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.45Ctt11sFalsef.png b/data/CLs/plots/omega_s/0.45Ctt11sFalsef.png index 9d9ce21..fe19eb6 100644 --- a/data/CLs/plots/omega_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/omega_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.49Ctt12sTruef.png b/data/CLs/plots/omega_s/0.49Ctt12sTruef.png index 2ec86cb..cb47cc3 100644 --- a/data/CLs/plots/omega_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/omega_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.49Ctt13sFalsef.png b/data/CLs/plots/omega_s/0.49Ctt13sFalsef.png index fdc3309..4316a97 100644 --- a/data/CLs/plots/omega_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/omega_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.53Ctt14sTruef.png b/data/CLs/plots/omega_s/0.53Ctt14sTruef.png index 390756f..65e7bf1 100644 --- a/data/CLs/plots/omega_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/omega_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.53Ctt15sFalsef.png b/data/CLs/plots/omega_s/0.53Ctt15sFalsef.png index 94e1631..2b30ad5 100644 --- a/data/CLs/plots/omega_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/omega_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.56Ctt16sTruef.png b/data/CLs/plots/omega_s/0.56Ctt16sTruef.png index 5ab45b9..ec7bc17 100644 --- a/data/CLs/plots/omega_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/omega_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.56Ctt17sFalsef.png b/data/CLs/plots/omega_s/0.56Ctt17sFalsef.png index dc5b65b..cdeecdd 100644 --- a/data/CLs/plots/omega_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/omega_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.59Ctt18sTruef.png b/data/CLs/plots/omega_s/0.59Ctt18sTruef.png index bba4c09..fbda9da 100644 --- a/data/CLs/plots/omega_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/omega_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.59Ctt19sFalsef.png b/data/CLs/plots/omega_s/0.59Ctt19sFalsef.png index ad84a21..419dc9f 100644 --- a/data/CLs/plots/omega_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/omega_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.62Ctt20sTruef.png b/data/CLs/plots/omega_s/0.62Ctt20sTruef.png index cde5151..6891446 100644 --- a/data/CLs/plots/omega_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/omega_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.62Ctt21sFalsef.png b/data/CLs/plots/omega_s/0.62Ctt21sFalsef.png index fe0a62a..39d30e3 100644 --- a/data/CLs/plots/omega_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/omega_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.65Ctt22sTruef.png b/data/CLs/plots/omega_s/0.65Ctt22sTruef.png index 50f3f80..eec3066 100644 --- a/data/CLs/plots/omega_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/omega_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.65Ctt23sFalsef.png b/data/CLs/plots/omega_s/0.65Ctt23sFalsef.png index 0a4381e..3dfd620 100644 --- a/data/CLs/plots/omega_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/omega_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.68Ctt24sTruef.png b/data/CLs/plots/omega_s/0.68Ctt24sTruef.png index 2934049..94c48a0 100644 --- a/data/CLs/plots/omega_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/omega_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.68Ctt25sFalsef.png b/data/CLs/plots/omega_s/0.68Ctt25sFalsef.png index 8b31e8c..0d08675 100644 --- a/data/CLs/plots/omega_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/omega_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.70Ctt26sTruef.png b/data/CLs/plots/omega_s/0.70Ctt26sTruef.png index 928d89c..5d8ac4e 100644 --- a/data/CLs/plots/omega_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/omega_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.70Ctt27sFalsef.png b/data/CLs/plots/omega_s/0.70Ctt27sFalsef.png index 12f4bef..e5f6c3b 100644 --- a/data/CLs/plots/omega_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/omega_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.73Ctt28sTruef.png b/data/CLs/plots/omega_s/0.73Ctt28sTruef.png index 4a3615e..70bd928 100644 --- a/data/CLs/plots/omega_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/omega_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.73Ctt29sFalsef.png b/data/CLs/plots/omega_s/0.73Ctt29sFalsef.png index c3bec2c..856e298 100644 --- a/data/CLs/plots/omega_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/omega_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.75Ctt30sTruef.png b/data/CLs/plots/omega_s/0.75Ctt30sTruef.png index 804ad49..ec83ef1 100644 --- a/data/CLs/plots/omega_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/omega_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.75Ctt31sFalsef.png b/data/CLs/plots/omega_s/0.75Ctt31sFalsef.png index 410de72..bdc506b 100644 --- a/data/CLs/plots/omega_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/omega_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.78Ctt32sTruef.png b/data/CLs/plots/omega_s/0.78Ctt32sTruef.png index 5d01e56..63036ec 100644 --- a/data/CLs/plots/omega_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/omega_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.78Ctt33sFalsef.png b/data/CLs/plots/omega_s/0.78Ctt33sFalsef.png index 2f31671..e4758d2 100644 --- a/data/CLs/plots/omega_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/omega_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.80Ctt34sTruef.png b/data/CLs/plots/omega_s/0.80Ctt34sTruef.png index 0c6489a..f06a496 100644 --- a/data/CLs/plots/omega_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/omega_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.80Ctt35sFalsef.png b/data/CLs/plots/omega_s/0.80Ctt35sFalsef.png index 0296ac4..40b09e7 100644 --- a/data/CLs/plots/omega_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/omega_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.82Ctt36sTruef.png b/data/CLs/plots/omega_s/0.82Ctt36sTruef.png index cae212f..23abf82 100644 --- a/data/CLs/plots/omega_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/omega_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.82Ctt37sFalsef.png b/data/CLs/plots/omega_s/0.82Ctt37sFalsef.png index 94c577a..58eafac 100644 --- a/data/CLs/plots/omega_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/omega_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.85Ctt38sTruef.png b/data/CLs/plots/omega_s/0.85Ctt38sTruef.png index 71de207..adb9d1a 100644 --- a/data/CLs/plots/omega_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/omega_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/omega_s/0.85Ctt39sFalsef.png b/data/CLs/plots/omega_s/0.85Ctt39sFalsef.png index 9fac01f..3d19c1c 100644 --- a/data/CLs/plots/omega_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/omega_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.00Ctt0sTruef.png b/data/CLs/plots/p3770_p/0.00Ctt0sTruef.png index 6137196..135744a 100644 --- a/data/CLs/plots/p3770_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p3770_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.00Ctt1sFalsef.png b/data/CLs/plots/p3770_p/0.00Ctt1sFalsef.png index 704c942..3810e52 100644 --- a/data/CLs/plots/p3770_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p3770_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.25Ctt2sTruef.png b/data/CLs/plots/p3770_p/0.25Ctt2sTruef.png index e663ebd..63f74bd 100644 --- a/data/CLs/plots/p3770_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p3770_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.25Ctt3sFalsef.png b/data/CLs/plots/p3770_p/0.25Ctt3sFalsef.png index ea2cf60..100ab2a 100644 --- a/data/CLs/plots/p3770_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p3770_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.31Ctt4sTruef.png b/data/CLs/plots/p3770_p/0.31Ctt4sTruef.png index 0443612..94e5289 100644 --- a/data/CLs/plots/p3770_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p3770_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.31Ctt5sFalsef.png b/data/CLs/plots/p3770_p/0.31Ctt5sFalsef.png index 04dbb6f..c017384 100644 --- a/data/CLs/plots/p3770_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p3770_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.36Ctt6sTruef.png b/data/CLs/plots/p3770_p/0.36Ctt6sTruef.png index be921d6..6c10d7e 100644 --- a/data/CLs/plots/p3770_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p3770_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.36Ctt7sFalsef.png b/data/CLs/plots/p3770_p/0.36Ctt7sFalsef.png index e413967..b48e8b2 100644 --- a/data/CLs/plots/p3770_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p3770_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.41Ctt8sTruef.png b/data/CLs/plots/p3770_p/0.41Ctt8sTruef.png index 3229008..0fce0f5 100644 --- a/data/CLs/plots/p3770_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p3770_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.41Ctt9sFalsef.png b/data/CLs/plots/p3770_p/0.41Ctt9sFalsef.png index 16ab75f..1afd079 100644 --- a/data/CLs/plots/p3770_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p3770_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.45Ctt10sTruef.png b/data/CLs/plots/p3770_p/0.45Ctt10sTruef.png index b4a5aef..cfacd35 100644 --- a/data/CLs/plots/p3770_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p3770_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.45Ctt11sFalsef.png b/data/CLs/plots/p3770_p/0.45Ctt11sFalsef.png index 843e465..7805cbf 100644 --- a/data/CLs/plots/p3770_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p3770_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.49Ctt12sTruef.png b/data/CLs/plots/p3770_p/0.49Ctt12sTruef.png index b0fdd0f..b4e7819 100644 --- a/data/CLs/plots/p3770_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p3770_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.49Ctt13sFalsef.png b/data/CLs/plots/p3770_p/0.49Ctt13sFalsef.png index d06353b..381162f 100644 --- a/data/CLs/plots/p3770_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p3770_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.53Ctt14sTruef.png b/data/CLs/plots/p3770_p/0.53Ctt14sTruef.png index 3b5c60b..b73c0ab 100644 --- a/data/CLs/plots/p3770_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p3770_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.53Ctt15sFalsef.png b/data/CLs/plots/p3770_p/0.53Ctt15sFalsef.png index 5a084a0..e252fd3 100644 --- a/data/CLs/plots/p3770_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p3770_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.56Ctt16sTruef.png b/data/CLs/plots/p3770_p/0.56Ctt16sTruef.png index 9c1d317..06f5031 100644 --- a/data/CLs/plots/p3770_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p3770_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.56Ctt17sFalsef.png b/data/CLs/plots/p3770_p/0.56Ctt17sFalsef.png index 592bf68..75f6814 100644 --- a/data/CLs/plots/p3770_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p3770_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.59Ctt18sTruef.png b/data/CLs/plots/p3770_p/0.59Ctt18sTruef.png index 24aaab4..d431d97 100644 --- a/data/CLs/plots/p3770_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p3770_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.59Ctt19sFalsef.png b/data/CLs/plots/p3770_p/0.59Ctt19sFalsef.png index d256667..d68a773 100644 --- a/data/CLs/plots/p3770_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p3770_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.62Ctt20sTruef.png b/data/CLs/plots/p3770_p/0.62Ctt20sTruef.png index 1df7bd1..7c06f2a 100644 --- a/data/CLs/plots/p3770_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p3770_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.62Ctt21sFalsef.png b/data/CLs/plots/p3770_p/0.62Ctt21sFalsef.png index 8d95194..f9031b8 100644 --- a/data/CLs/plots/p3770_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p3770_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.65Ctt22sTruef.png b/data/CLs/plots/p3770_p/0.65Ctt22sTruef.png index c5b6860..8a636d6 100644 --- a/data/CLs/plots/p3770_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p3770_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.65Ctt23sFalsef.png b/data/CLs/plots/p3770_p/0.65Ctt23sFalsef.png index 13ca184..f95d54c 100644 --- a/data/CLs/plots/p3770_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p3770_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.68Ctt24sTruef.png b/data/CLs/plots/p3770_p/0.68Ctt24sTruef.png index e1cd15c..a1c5214 100644 --- a/data/CLs/plots/p3770_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p3770_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.68Ctt25sFalsef.png b/data/CLs/plots/p3770_p/0.68Ctt25sFalsef.png index 1ea8fe5..8df245f 100644 --- a/data/CLs/plots/p3770_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p3770_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.70Ctt26sTruef.png b/data/CLs/plots/p3770_p/0.70Ctt26sTruef.png index 2c81cde..932be82 100644 --- a/data/CLs/plots/p3770_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p3770_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.70Ctt27sFalsef.png b/data/CLs/plots/p3770_p/0.70Ctt27sFalsef.png index 4abac8d..9b60ea2 100644 --- a/data/CLs/plots/p3770_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p3770_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.73Ctt28sTruef.png b/data/CLs/plots/p3770_p/0.73Ctt28sTruef.png index 15b8786..56feea0 100644 --- a/data/CLs/plots/p3770_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p3770_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.73Ctt29sFalsef.png b/data/CLs/plots/p3770_p/0.73Ctt29sFalsef.png index 7d0438b..a7a0a74 100644 --- a/data/CLs/plots/p3770_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p3770_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.75Ctt30sTruef.png b/data/CLs/plots/p3770_p/0.75Ctt30sTruef.png index ec7b732..b9e8de9 100644 --- a/data/CLs/plots/p3770_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p3770_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.75Ctt31sFalsef.png b/data/CLs/plots/p3770_p/0.75Ctt31sFalsef.png index 0c0d8c0..33223d2 100644 --- a/data/CLs/plots/p3770_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p3770_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.78Ctt32sTruef.png b/data/CLs/plots/p3770_p/0.78Ctt32sTruef.png index f86185a..ef4d85b 100644 --- a/data/CLs/plots/p3770_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p3770_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.78Ctt33sFalsef.png b/data/CLs/plots/p3770_p/0.78Ctt33sFalsef.png index dd32d41..6dcb29f 100644 --- a/data/CLs/plots/p3770_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p3770_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.80Ctt34sTruef.png b/data/CLs/plots/p3770_p/0.80Ctt34sTruef.png index f24a654..4655b20 100644 --- a/data/CLs/plots/p3770_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p3770_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.80Ctt35sFalsef.png b/data/CLs/plots/p3770_p/0.80Ctt35sFalsef.png index a4f58cc..c3ec6af 100644 --- a/data/CLs/plots/p3770_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p3770_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.82Ctt36sTruef.png b/data/CLs/plots/p3770_p/0.82Ctt36sTruef.png index 938ceba..c53860e 100644 --- a/data/CLs/plots/p3770_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p3770_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.82Ctt37sFalsef.png b/data/CLs/plots/p3770_p/0.82Ctt37sFalsef.png index fc23b32..d916388 100644 --- a/data/CLs/plots/p3770_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p3770_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.85Ctt38sTruef.png b/data/CLs/plots/p3770_p/0.85Ctt38sTruef.png index 9b55e7e..0f4c51a 100644 --- a/data/CLs/plots/p3770_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p3770_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_p/0.85Ctt39sFalsef.png b/data/CLs/plots/p3770_p/0.85Ctt39sFalsef.png index 1178f5d..0c2823f 100644 --- a/data/CLs/plots/p3770_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p3770_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.00Ctt0sTruef.png b/data/CLs/plots/p3770_s/0.00Ctt0sTruef.png index 76b90c1..4d030dc 100644 --- a/data/CLs/plots/p3770_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p3770_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.00Ctt1sFalsef.png b/data/CLs/plots/p3770_s/0.00Ctt1sFalsef.png index ca691f8..2a0f3c0 100644 --- a/data/CLs/plots/p3770_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p3770_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.25Ctt2sTruef.png b/data/CLs/plots/p3770_s/0.25Ctt2sTruef.png index 5181431..4e957e1 100644 --- a/data/CLs/plots/p3770_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p3770_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.25Ctt3sFalsef.png b/data/CLs/plots/p3770_s/0.25Ctt3sFalsef.png index 4520cc2..7c4ca6e 100644 --- a/data/CLs/plots/p3770_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p3770_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.31Ctt4sTruef.png b/data/CLs/plots/p3770_s/0.31Ctt4sTruef.png index ec97850..7308180 100644 --- a/data/CLs/plots/p3770_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p3770_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.31Ctt5sFalsef.png b/data/CLs/plots/p3770_s/0.31Ctt5sFalsef.png index 51bae4d..dbde442 100644 --- a/data/CLs/plots/p3770_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p3770_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.36Ctt6sTruef.png b/data/CLs/plots/p3770_s/0.36Ctt6sTruef.png index b112eae..c87b17f 100644 --- a/data/CLs/plots/p3770_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p3770_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.36Ctt7sFalsef.png b/data/CLs/plots/p3770_s/0.36Ctt7sFalsef.png index f954ba8..09d2b71 100644 --- a/data/CLs/plots/p3770_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p3770_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.41Ctt8sTruef.png b/data/CLs/plots/p3770_s/0.41Ctt8sTruef.png index 157045e..2bfbe6f 100644 --- a/data/CLs/plots/p3770_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p3770_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.41Ctt9sFalsef.png b/data/CLs/plots/p3770_s/0.41Ctt9sFalsef.png index ec9538e..18eb865 100644 --- a/data/CLs/plots/p3770_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p3770_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.45Ctt10sTruef.png b/data/CLs/plots/p3770_s/0.45Ctt10sTruef.png index 3eec71e..c875a97 100644 --- a/data/CLs/plots/p3770_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p3770_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.45Ctt11sFalsef.png b/data/CLs/plots/p3770_s/0.45Ctt11sFalsef.png index 316457a..5dd06ba 100644 --- a/data/CLs/plots/p3770_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p3770_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.49Ctt12sTruef.png b/data/CLs/plots/p3770_s/0.49Ctt12sTruef.png index cc600b6..072a06c 100644 --- a/data/CLs/plots/p3770_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p3770_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.49Ctt13sFalsef.png b/data/CLs/plots/p3770_s/0.49Ctt13sFalsef.png index 3d8d133..97f7338 100644 --- a/data/CLs/plots/p3770_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p3770_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.53Ctt14sTruef.png b/data/CLs/plots/p3770_s/0.53Ctt14sTruef.png index 0fc0edb..cc9807f 100644 --- a/data/CLs/plots/p3770_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p3770_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.53Ctt15sFalsef.png b/data/CLs/plots/p3770_s/0.53Ctt15sFalsef.png index 7d0f71b..b4779a3 100644 --- a/data/CLs/plots/p3770_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p3770_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.56Ctt16sTruef.png b/data/CLs/plots/p3770_s/0.56Ctt16sTruef.png index bb85c12..c75f7b2 100644 --- a/data/CLs/plots/p3770_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p3770_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.56Ctt17sFalsef.png b/data/CLs/plots/p3770_s/0.56Ctt17sFalsef.png index b67ad45..d4ab93c 100644 --- a/data/CLs/plots/p3770_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p3770_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.59Ctt18sTruef.png b/data/CLs/plots/p3770_s/0.59Ctt18sTruef.png index 74a076d..92e3745 100644 --- a/data/CLs/plots/p3770_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p3770_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.59Ctt19sFalsef.png b/data/CLs/plots/p3770_s/0.59Ctt19sFalsef.png index 8432085..751c514 100644 --- a/data/CLs/plots/p3770_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p3770_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.62Ctt20sTruef.png b/data/CLs/plots/p3770_s/0.62Ctt20sTruef.png index d012b73..11fc4a3 100644 --- a/data/CLs/plots/p3770_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p3770_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.62Ctt21sFalsef.png b/data/CLs/plots/p3770_s/0.62Ctt21sFalsef.png index d7bcac2..64111a6 100644 --- a/data/CLs/plots/p3770_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p3770_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.65Ctt22sTruef.png b/data/CLs/plots/p3770_s/0.65Ctt22sTruef.png index 4dac98f..bd117e9 100644 --- a/data/CLs/plots/p3770_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p3770_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.65Ctt23sFalsef.png b/data/CLs/plots/p3770_s/0.65Ctt23sFalsef.png index c0239bc..2352d2d 100644 --- a/data/CLs/plots/p3770_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p3770_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.68Ctt24sTruef.png b/data/CLs/plots/p3770_s/0.68Ctt24sTruef.png index 809d3eb..b0c38be 100644 --- a/data/CLs/plots/p3770_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p3770_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.68Ctt25sFalsef.png b/data/CLs/plots/p3770_s/0.68Ctt25sFalsef.png index 0ece4a6..6a0fa77 100644 --- a/data/CLs/plots/p3770_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p3770_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.70Ctt26sTruef.png b/data/CLs/plots/p3770_s/0.70Ctt26sTruef.png index 4cc9d0e..69286b3 100644 --- a/data/CLs/plots/p3770_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p3770_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.70Ctt27sFalsef.png b/data/CLs/plots/p3770_s/0.70Ctt27sFalsef.png index 6d54827..5158316 100644 --- a/data/CLs/plots/p3770_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p3770_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.73Ctt28sTruef.png b/data/CLs/plots/p3770_s/0.73Ctt28sTruef.png index 5030796..b18ff6c 100644 --- a/data/CLs/plots/p3770_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p3770_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.73Ctt29sFalsef.png b/data/CLs/plots/p3770_s/0.73Ctt29sFalsef.png index 7fb4185..6d24d94 100644 --- a/data/CLs/plots/p3770_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p3770_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.75Ctt30sTruef.png b/data/CLs/plots/p3770_s/0.75Ctt30sTruef.png index 4497532..c2ba983 100644 --- a/data/CLs/plots/p3770_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p3770_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.75Ctt31sFalsef.png b/data/CLs/plots/p3770_s/0.75Ctt31sFalsef.png index e335d17..a8a8fce 100644 --- a/data/CLs/plots/p3770_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p3770_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.78Ctt32sTruef.png b/data/CLs/plots/p3770_s/0.78Ctt32sTruef.png index d918a49..84563c7 100644 --- a/data/CLs/plots/p3770_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p3770_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.78Ctt33sFalsef.png b/data/CLs/plots/p3770_s/0.78Ctt33sFalsef.png index e1d8a63..7437619 100644 --- a/data/CLs/plots/p3770_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p3770_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.80Ctt34sTruef.png b/data/CLs/plots/p3770_s/0.80Ctt34sTruef.png index f2a4fa1..29e444b 100644 --- a/data/CLs/plots/p3770_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p3770_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.80Ctt35sFalsef.png b/data/CLs/plots/p3770_s/0.80Ctt35sFalsef.png index 07524ba..07804c7 100644 --- a/data/CLs/plots/p3770_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p3770_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.82Ctt36sTruef.png b/data/CLs/plots/p3770_s/0.82Ctt36sTruef.png index 7c87be7..61b616a 100644 --- a/data/CLs/plots/p3770_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p3770_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.82Ctt37sFalsef.png b/data/CLs/plots/p3770_s/0.82Ctt37sFalsef.png index 895350e..9948979 100644 --- a/data/CLs/plots/p3770_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p3770_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.85Ctt38sTruef.png b/data/CLs/plots/p3770_s/0.85Ctt38sTruef.png index 6621388..605ba05 100644 --- a/data/CLs/plots/p3770_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p3770_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p3770_s/0.85Ctt39sFalsef.png b/data/CLs/plots/p3770_s/0.85Ctt39sFalsef.png index c18c3a5..079b78c 100644 --- a/data/CLs/plots/p3770_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p3770_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.00Ctt0sTruef.png b/data/CLs/plots/p4040_p/0.00Ctt0sTruef.png index 8b618d7..adbe131 100644 --- a/data/CLs/plots/p4040_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p4040_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.00Ctt1sFalsef.png b/data/CLs/plots/p4040_p/0.00Ctt1sFalsef.png index 31048bc..7a3b094 100644 --- a/data/CLs/plots/p4040_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p4040_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.25Ctt2sTruef.png b/data/CLs/plots/p4040_p/0.25Ctt2sTruef.png index 93fbbd1..2f22ccd 100644 --- a/data/CLs/plots/p4040_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p4040_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.25Ctt3sFalsef.png b/data/CLs/plots/p4040_p/0.25Ctt3sFalsef.png index 0182a0d..36c0c3e 100644 --- a/data/CLs/plots/p4040_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p4040_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.31Ctt4sTruef.png b/data/CLs/plots/p4040_p/0.31Ctt4sTruef.png index 46a9b74..8769eb4 100644 --- a/data/CLs/plots/p4040_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p4040_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.31Ctt5sFalsef.png b/data/CLs/plots/p4040_p/0.31Ctt5sFalsef.png index be54550..07194d2 100644 --- a/data/CLs/plots/p4040_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p4040_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.36Ctt6sTruef.png b/data/CLs/plots/p4040_p/0.36Ctt6sTruef.png index c1f08f3..4d0bb4a 100644 --- a/data/CLs/plots/p4040_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p4040_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.36Ctt7sFalsef.png b/data/CLs/plots/p4040_p/0.36Ctt7sFalsef.png index b042504..359813e 100644 --- a/data/CLs/plots/p4040_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p4040_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.41Ctt8sTruef.png b/data/CLs/plots/p4040_p/0.41Ctt8sTruef.png index 1945489..af00b7f 100644 --- a/data/CLs/plots/p4040_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p4040_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.41Ctt9sFalsef.png b/data/CLs/plots/p4040_p/0.41Ctt9sFalsef.png index 6e01d42..16001a4 100644 --- a/data/CLs/plots/p4040_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p4040_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.45Ctt10sTruef.png b/data/CLs/plots/p4040_p/0.45Ctt10sTruef.png index bc3717a..ad906a1 100644 --- a/data/CLs/plots/p4040_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p4040_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.45Ctt11sFalsef.png b/data/CLs/plots/p4040_p/0.45Ctt11sFalsef.png index 8fce110..d8d39bd 100644 --- a/data/CLs/plots/p4040_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p4040_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.49Ctt12sTruef.png b/data/CLs/plots/p4040_p/0.49Ctt12sTruef.png index 48a53a9..3fbca36 100644 --- a/data/CLs/plots/p4040_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p4040_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.49Ctt13sFalsef.png b/data/CLs/plots/p4040_p/0.49Ctt13sFalsef.png index 8a16d30..057ea63 100644 --- a/data/CLs/plots/p4040_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p4040_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.53Ctt14sTruef.png b/data/CLs/plots/p4040_p/0.53Ctt14sTruef.png index 0a6a350..be3c024 100644 --- a/data/CLs/plots/p4040_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p4040_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.53Ctt15sFalsef.png b/data/CLs/plots/p4040_p/0.53Ctt15sFalsef.png index 5263896..4d7b5c0 100644 --- a/data/CLs/plots/p4040_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p4040_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.56Ctt16sTruef.png b/data/CLs/plots/p4040_p/0.56Ctt16sTruef.png index 38d33c8..fa8226e 100644 --- a/data/CLs/plots/p4040_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p4040_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.56Ctt17sFalsef.png b/data/CLs/plots/p4040_p/0.56Ctt17sFalsef.png index f5652f6..639bc69 100644 --- a/data/CLs/plots/p4040_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p4040_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.59Ctt18sTruef.png b/data/CLs/plots/p4040_p/0.59Ctt18sTruef.png index 3a30bbf..00ecc9e 100644 --- a/data/CLs/plots/p4040_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p4040_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.59Ctt19sFalsef.png b/data/CLs/plots/p4040_p/0.59Ctt19sFalsef.png index 69d35f2..c12bbf1 100644 --- a/data/CLs/plots/p4040_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p4040_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.62Ctt20sTruef.png b/data/CLs/plots/p4040_p/0.62Ctt20sTruef.png index 3e417cb..8a49b9b 100644 --- a/data/CLs/plots/p4040_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p4040_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.62Ctt21sFalsef.png b/data/CLs/plots/p4040_p/0.62Ctt21sFalsef.png index d3b06ae..59ffe4f 100644 --- a/data/CLs/plots/p4040_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p4040_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.65Ctt22sTruef.png b/data/CLs/plots/p4040_p/0.65Ctt22sTruef.png index e5f86e9..1a82547 100644 --- a/data/CLs/plots/p4040_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p4040_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.65Ctt23sFalsef.png b/data/CLs/plots/p4040_p/0.65Ctt23sFalsef.png index 61af5c3..dc0d98d 100644 --- a/data/CLs/plots/p4040_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p4040_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.68Ctt24sTruef.png b/data/CLs/plots/p4040_p/0.68Ctt24sTruef.png index 8958e4e..60c8c96 100644 --- a/data/CLs/plots/p4040_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p4040_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.68Ctt25sFalsef.png b/data/CLs/plots/p4040_p/0.68Ctt25sFalsef.png index 1dcf047..a7e20d9 100644 --- a/data/CLs/plots/p4040_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p4040_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.70Ctt26sTruef.png b/data/CLs/plots/p4040_p/0.70Ctt26sTruef.png index 8baa80b..adca084 100644 --- a/data/CLs/plots/p4040_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p4040_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.70Ctt27sFalsef.png b/data/CLs/plots/p4040_p/0.70Ctt27sFalsef.png index 06a011d..b6523bc 100644 --- a/data/CLs/plots/p4040_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p4040_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.73Ctt28sTruef.png b/data/CLs/plots/p4040_p/0.73Ctt28sTruef.png index 0bdbcfc..b202c5a 100644 --- a/data/CLs/plots/p4040_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p4040_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.73Ctt29sFalsef.png b/data/CLs/plots/p4040_p/0.73Ctt29sFalsef.png index b19d8df..430482a 100644 --- a/data/CLs/plots/p4040_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p4040_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.75Ctt30sTruef.png b/data/CLs/plots/p4040_p/0.75Ctt30sTruef.png index 0b45e9a..a76ca43 100644 --- a/data/CLs/plots/p4040_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p4040_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.75Ctt31sFalsef.png b/data/CLs/plots/p4040_p/0.75Ctt31sFalsef.png index 0b48a0a..568bf20 100644 --- a/data/CLs/plots/p4040_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p4040_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.78Ctt32sTruef.png b/data/CLs/plots/p4040_p/0.78Ctt32sTruef.png index 5b1c965..4bc927f 100644 --- a/data/CLs/plots/p4040_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p4040_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.78Ctt33sFalsef.png b/data/CLs/plots/p4040_p/0.78Ctt33sFalsef.png index 98d13b7..9f318cd 100644 --- a/data/CLs/plots/p4040_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p4040_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.80Ctt34sTruef.png b/data/CLs/plots/p4040_p/0.80Ctt34sTruef.png index a4f423d..5eade6d 100644 --- a/data/CLs/plots/p4040_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p4040_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.80Ctt35sFalsef.png b/data/CLs/plots/p4040_p/0.80Ctt35sFalsef.png index 35ac36b..b526ae4 100644 --- a/data/CLs/plots/p4040_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p4040_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.82Ctt36sTruef.png b/data/CLs/plots/p4040_p/0.82Ctt36sTruef.png index c655e05..1ead899 100644 --- a/data/CLs/plots/p4040_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p4040_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.82Ctt37sFalsef.png b/data/CLs/plots/p4040_p/0.82Ctt37sFalsef.png index c6311e6..5f32606 100644 --- a/data/CLs/plots/p4040_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p4040_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.85Ctt38sTruef.png b/data/CLs/plots/p4040_p/0.85Ctt38sTruef.png index 4843e5d..8f6d28d 100644 --- a/data/CLs/plots/p4040_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p4040_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_p/0.85Ctt39sFalsef.png b/data/CLs/plots/p4040_p/0.85Ctt39sFalsef.png index 45560cd..24ae0af 100644 --- a/data/CLs/plots/p4040_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p4040_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.00Ctt0sTruef.png b/data/CLs/plots/p4040_s/0.00Ctt0sTruef.png index d9f750d..155d0b6 100644 --- a/data/CLs/plots/p4040_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p4040_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.00Ctt1sFalsef.png b/data/CLs/plots/p4040_s/0.00Ctt1sFalsef.png index 02a1c6e..e4679ea 100644 --- a/data/CLs/plots/p4040_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p4040_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.25Ctt2sTruef.png b/data/CLs/plots/p4040_s/0.25Ctt2sTruef.png index 955922e..e61c285 100644 --- a/data/CLs/plots/p4040_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p4040_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.25Ctt3sFalsef.png b/data/CLs/plots/p4040_s/0.25Ctt3sFalsef.png index fbd573d..1a61e60 100644 --- a/data/CLs/plots/p4040_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p4040_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.31Ctt4sTruef.png b/data/CLs/plots/p4040_s/0.31Ctt4sTruef.png index 33b3302..50f2b0d 100644 --- a/data/CLs/plots/p4040_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p4040_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.31Ctt5sFalsef.png b/data/CLs/plots/p4040_s/0.31Ctt5sFalsef.png index 574f21a..ea0a507 100644 --- a/data/CLs/plots/p4040_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p4040_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.36Ctt6sTruef.png b/data/CLs/plots/p4040_s/0.36Ctt6sTruef.png index 2488f9b..64bee8c 100644 --- a/data/CLs/plots/p4040_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p4040_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.36Ctt7sFalsef.png b/data/CLs/plots/p4040_s/0.36Ctt7sFalsef.png index b6b0ca5..a4c5ea0 100644 --- a/data/CLs/plots/p4040_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p4040_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.41Ctt8sTruef.png b/data/CLs/plots/p4040_s/0.41Ctt8sTruef.png index b96a3de..31b48b3 100644 --- a/data/CLs/plots/p4040_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p4040_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.41Ctt9sFalsef.png b/data/CLs/plots/p4040_s/0.41Ctt9sFalsef.png index 200433e..2b04d23 100644 --- a/data/CLs/plots/p4040_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p4040_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.45Ctt10sTruef.png b/data/CLs/plots/p4040_s/0.45Ctt10sTruef.png index 2a0329b..a34c50f 100644 --- a/data/CLs/plots/p4040_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p4040_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.45Ctt11sFalsef.png b/data/CLs/plots/p4040_s/0.45Ctt11sFalsef.png index cd90ad8..3d16e6c 100644 --- a/data/CLs/plots/p4040_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p4040_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.49Ctt12sTruef.png b/data/CLs/plots/p4040_s/0.49Ctt12sTruef.png index a29f21d..aa7dccd 100644 --- a/data/CLs/plots/p4040_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p4040_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.49Ctt13sFalsef.png b/data/CLs/plots/p4040_s/0.49Ctt13sFalsef.png index db92a86..eae870a 100644 --- a/data/CLs/plots/p4040_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p4040_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.53Ctt14sTruef.png b/data/CLs/plots/p4040_s/0.53Ctt14sTruef.png index 441ea36..4f50d0c 100644 --- a/data/CLs/plots/p4040_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p4040_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.53Ctt15sFalsef.png b/data/CLs/plots/p4040_s/0.53Ctt15sFalsef.png index 66d40f5..d5d6915 100644 --- a/data/CLs/plots/p4040_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p4040_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.56Ctt16sTruef.png b/data/CLs/plots/p4040_s/0.56Ctt16sTruef.png index 632f912..2b6f271 100644 --- a/data/CLs/plots/p4040_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p4040_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.56Ctt17sFalsef.png b/data/CLs/plots/p4040_s/0.56Ctt17sFalsef.png index 3fc903d..5da70d5 100644 --- a/data/CLs/plots/p4040_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p4040_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.59Ctt18sTruef.png b/data/CLs/plots/p4040_s/0.59Ctt18sTruef.png index 4894c68..ca344b8 100644 --- a/data/CLs/plots/p4040_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p4040_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.59Ctt19sFalsef.png b/data/CLs/plots/p4040_s/0.59Ctt19sFalsef.png index 73a52fd..c69a805 100644 --- a/data/CLs/plots/p4040_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p4040_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.62Ctt20sTruef.png b/data/CLs/plots/p4040_s/0.62Ctt20sTruef.png index ec6300f..32e2ca6 100644 --- a/data/CLs/plots/p4040_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p4040_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.62Ctt21sFalsef.png b/data/CLs/plots/p4040_s/0.62Ctt21sFalsef.png index 47043d8..4f04913 100644 --- a/data/CLs/plots/p4040_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p4040_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.65Ctt22sTruef.png b/data/CLs/plots/p4040_s/0.65Ctt22sTruef.png index c4e54d2..debc1bb 100644 --- a/data/CLs/plots/p4040_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p4040_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.65Ctt23sFalsef.png b/data/CLs/plots/p4040_s/0.65Ctt23sFalsef.png index e6a692b..d266ec2 100644 --- a/data/CLs/plots/p4040_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p4040_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.68Ctt24sTruef.png b/data/CLs/plots/p4040_s/0.68Ctt24sTruef.png index 6f6c64b..08dd0f7 100644 --- a/data/CLs/plots/p4040_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p4040_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.68Ctt25sFalsef.png b/data/CLs/plots/p4040_s/0.68Ctt25sFalsef.png index 319adee..1291aad 100644 --- a/data/CLs/plots/p4040_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p4040_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.70Ctt26sTruef.png b/data/CLs/plots/p4040_s/0.70Ctt26sTruef.png index 2a5002c..14a35e6 100644 --- a/data/CLs/plots/p4040_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p4040_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.70Ctt27sFalsef.png b/data/CLs/plots/p4040_s/0.70Ctt27sFalsef.png index 387754b..f8525ef 100644 --- a/data/CLs/plots/p4040_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p4040_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.73Ctt28sTruef.png b/data/CLs/plots/p4040_s/0.73Ctt28sTruef.png index 3c23db7..9953576 100644 --- a/data/CLs/plots/p4040_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p4040_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.73Ctt29sFalsef.png b/data/CLs/plots/p4040_s/0.73Ctt29sFalsef.png index a7400d4..8ee51bb 100644 --- a/data/CLs/plots/p4040_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p4040_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.75Ctt30sTruef.png b/data/CLs/plots/p4040_s/0.75Ctt30sTruef.png index 49ce3a1..ff8605a 100644 --- a/data/CLs/plots/p4040_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p4040_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.75Ctt31sFalsef.png b/data/CLs/plots/p4040_s/0.75Ctt31sFalsef.png index 03a746b..fc9cc62 100644 --- a/data/CLs/plots/p4040_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p4040_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.78Ctt32sTruef.png b/data/CLs/plots/p4040_s/0.78Ctt32sTruef.png index 3e6ff54..d4c9083 100644 --- a/data/CLs/plots/p4040_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p4040_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.78Ctt33sFalsef.png b/data/CLs/plots/p4040_s/0.78Ctt33sFalsef.png index 64c7f72..f706824 100644 --- a/data/CLs/plots/p4040_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p4040_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.80Ctt34sTruef.png b/data/CLs/plots/p4040_s/0.80Ctt34sTruef.png index bf9ca51..7ee6ac0 100644 --- a/data/CLs/plots/p4040_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p4040_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.80Ctt35sFalsef.png b/data/CLs/plots/p4040_s/0.80Ctt35sFalsef.png index 4292e6b..11a299b 100644 --- a/data/CLs/plots/p4040_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p4040_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.82Ctt36sTruef.png b/data/CLs/plots/p4040_s/0.82Ctt36sTruef.png index c01c894..32cb81f 100644 --- a/data/CLs/plots/p4040_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p4040_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.82Ctt37sFalsef.png b/data/CLs/plots/p4040_s/0.82Ctt37sFalsef.png index 90b2cb2..d267a47 100644 --- a/data/CLs/plots/p4040_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p4040_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.85Ctt38sTruef.png b/data/CLs/plots/p4040_s/0.85Ctt38sTruef.png index db7147c..c300165 100644 --- a/data/CLs/plots/p4040_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p4040_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p4040_s/0.85Ctt39sFalsef.png b/data/CLs/plots/p4040_s/0.85Ctt39sFalsef.png index ed51607..cebc114 100644 --- a/data/CLs/plots/p4040_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p4040_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.00Ctt0sTruef.png b/data/CLs/plots/p4160_p/0.00Ctt0sTruef.png index e6e8e2e..b3c10a2 100644 --- a/data/CLs/plots/p4160_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p4160_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.00Ctt1sFalsef.png b/data/CLs/plots/p4160_p/0.00Ctt1sFalsef.png index 8518893..257e6c9 100644 --- a/data/CLs/plots/p4160_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p4160_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.25Ctt2sTruef.png b/data/CLs/plots/p4160_p/0.25Ctt2sTruef.png index 5aae9fe..69d5620 100644 --- a/data/CLs/plots/p4160_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p4160_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.25Ctt3sFalsef.png b/data/CLs/plots/p4160_p/0.25Ctt3sFalsef.png index 09af631..9f2be4f 100644 --- a/data/CLs/plots/p4160_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p4160_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.31Ctt4sTruef.png b/data/CLs/plots/p4160_p/0.31Ctt4sTruef.png index aab8475..1609481 100644 --- a/data/CLs/plots/p4160_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p4160_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.31Ctt5sFalsef.png b/data/CLs/plots/p4160_p/0.31Ctt5sFalsef.png index ecc812d..5503bf1 100644 --- a/data/CLs/plots/p4160_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p4160_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.36Ctt6sTruef.png b/data/CLs/plots/p4160_p/0.36Ctt6sTruef.png index ab6a27f..d2caa26 100644 --- a/data/CLs/plots/p4160_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p4160_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.36Ctt7sFalsef.png b/data/CLs/plots/p4160_p/0.36Ctt7sFalsef.png index 8562c2f..68b692e 100644 --- a/data/CLs/plots/p4160_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p4160_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.41Ctt8sTruef.png b/data/CLs/plots/p4160_p/0.41Ctt8sTruef.png index 41dc43d..be2cdb1 100644 --- a/data/CLs/plots/p4160_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p4160_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.41Ctt9sFalsef.png b/data/CLs/plots/p4160_p/0.41Ctt9sFalsef.png index da2615d..e7d6365 100644 --- a/data/CLs/plots/p4160_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p4160_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.45Ctt10sTruef.png b/data/CLs/plots/p4160_p/0.45Ctt10sTruef.png index 9767566..594a63c 100644 --- a/data/CLs/plots/p4160_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p4160_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.45Ctt11sFalsef.png b/data/CLs/plots/p4160_p/0.45Ctt11sFalsef.png index f96cfa6..add4aab 100644 --- a/data/CLs/plots/p4160_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p4160_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.49Ctt12sTruef.png b/data/CLs/plots/p4160_p/0.49Ctt12sTruef.png index 2bf8831..9509628 100644 --- a/data/CLs/plots/p4160_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p4160_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.49Ctt13sFalsef.png b/data/CLs/plots/p4160_p/0.49Ctt13sFalsef.png index 36d7755..578daf2 100644 --- a/data/CLs/plots/p4160_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p4160_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.53Ctt14sTruef.png b/data/CLs/plots/p4160_p/0.53Ctt14sTruef.png index 497c54e..8a1a007 100644 --- a/data/CLs/plots/p4160_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p4160_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.53Ctt15sFalsef.png b/data/CLs/plots/p4160_p/0.53Ctt15sFalsef.png index 51ed8eb..b3a63a3 100644 --- a/data/CLs/plots/p4160_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p4160_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.56Ctt16sTruef.png b/data/CLs/plots/p4160_p/0.56Ctt16sTruef.png index d140159..17cb93d 100644 --- a/data/CLs/plots/p4160_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p4160_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.56Ctt17sFalsef.png b/data/CLs/plots/p4160_p/0.56Ctt17sFalsef.png index e9ad431..4a4c4a0 100644 --- a/data/CLs/plots/p4160_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p4160_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.59Ctt18sTruef.png b/data/CLs/plots/p4160_p/0.59Ctt18sTruef.png index 235de14..0939697 100644 --- a/data/CLs/plots/p4160_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p4160_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.59Ctt19sFalsef.png b/data/CLs/plots/p4160_p/0.59Ctt19sFalsef.png index e4eba1f..9adf1f0 100644 --- a/data/CLs/plots/p4160_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p4160_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.62Ctt20sTruef.png b/data/CLs/plots/p4160_p/0.62Ctt20sTruef.png index 722d6ac..6bbbce3 100644 --- a/data/CLs/plots/p4160_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p4160_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.62Ctt21sFalsef.png b/data/CLs/plots/p4160_p/0.62Ctt21sFalsef.png index 3764fb8..84870ad 100644 --- a/data/CLs/plots/p4160_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p4160_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.65Ctt22sTruef.png b/data/CLs/plots/p4160_p/0.65Ctt22sTruef.png index 6797f4d..617d6cf 100644 --- a/data/CLs/plots/p4160_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p4160_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.65Ctt23sFalsef.png b/data/CLs/plots/p4160_p/0.65Ctt23sFalsef.png index a0daa74..b97932a 100644 --- a/data/CLs/plots/p4160_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p4160_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.68Ctt24sTruef.png b/data/CLs/plots/p4160_p/0.68Ctt24sTruef.png index b8821aa..ae2261e 100644 --- a/data/CLs/plots/p4160_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p4160_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.68Ctt25sFalsef.png b/data/CLs/plots/p4160_p/0.68Ctt25sFalsef.png index 46b6973..07523df 100644 --- a/data/CLs/plots/p4160_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p4160_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.70Ctt26sTruef.png b/data/CLs/plots/p4160_p/0.70Ctt26sTruef.png index 60a6525..2385335 100644 --- a/data/CLs/plots/p4160_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p4160_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.70Ctt27sFalsef.png b/data/CLs/plots/p4160_p/0.70Ctt27sFalsef.png index bce28fb..4649953 100644 --- a/data/CLs/plots/p4160_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p4160_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.73Ctt28sTruef.png b/data/CLs/plots/p4160_p/0.73Ctt28sTruef.png index 551e44c..dadf310 100644 --- a/data/CLs/plots/p4160_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p4160_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.73Ctt29sFalsef.png b/data/CLs/plots/p4160_p/0.73Ctt29sFalsef.png index a6e550c..9bbf533 100644 --- a/data/CLs/plots/p4160_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p4160_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.75Ctt30sTruef.png b/data/CLs/plots/p4160_p/0.75Ctt30sTruef.png index 8711084..6cbccf8 100644 --- a/data/CLs/plots/p4160_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p4160_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.75Ctt31sFalsef.png b/data/CLs/plots/p4160_p/0.75Ctt31sFalsef.png index 5a930aa..dfa6ec9 100644 --- a/data/CLs/plots/p4160_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p4160_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.78Ctt32sTruef.png b/data/CLs/plots/p4160_p/0.78Ctt32sTruef.png index d9e36e1..5eec3be 100644 --- a/data/CLs/plots/p4160_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p4160_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.78Ctt33sFalsef.png b/data/CLs/plots/p4160_p/0.78Ctt33sFalsef.png index 8963529..e301f50 100644 --- a/data/CLs/plots/p4160_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p4160_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.80Ctt34sTruef.png b/data/CLs/plots/p4160_p/0.80Ctt34sTruef.png index 4f421e5..798eff0 100644 --- a/data/CLs/plots/p4160_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p4160_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.80Ctt35sFalsef.png b/data/CLs/plots/p4160_p/0.80Ctt35sFalsef.png index f203ca7..ee6de3e 100644 --- a/data/CLs/plots/p4160_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p4160_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.82Ctt36sTruef.png b/data/CLs/plots/p4160_p/0.82Ctt36sTruef.png index fcf8098..4cf583c 100644 --- a/data/CLs/plots/p4160_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p4160_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.82Ctt37sFalsef.png b/data/CLs/plots/p4160_p/0.82Ctt37sFalsef.png index d872b77..d28a9c5 100644 --- a/data/CLs/plots/p4160_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p4160_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.85Ctt38sTruef.png b/data/CLs/plots/p4160_p/0.85Ctt38sTruef.png index 0b55ff5..415e528 100644 --- a/data/CLs/plots/p4160_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p4160_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_p/0.85Ctt39sFalsef.png b/data/CLs/plots/p4160_p/0.85Ctt39sFalsef.png index 47d4cc3..0457072 100644 --- a/data/CLs/plots/p4160_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p4160_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.00Ctt0sTruef.png b/data/CLs/plots/p4160_s/0.00Ctt0sTruef.png index 2aeb578..b8763e8 100644 --- a/data/CLs/plots/p4160_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p4160_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.00Ctt1sFalsef.png b/data/CLs/plots/p4160_s/0.00Ctt1sFalsef.png index 80d8738..39d93f5 100644 --- a/data/CLs/plots/p4160_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p4160_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.25Ctt2sTruef.png b/data/CLs/plots/p4160_s/0.25Ctt2sTruef.png index bf0c519..6cb1470 100644 --- a/data/CLs/plots/p4160_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p4160_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.25Ctt3sFalsef.png b/data/CLs/plots/p4160_s/0.25Ctt3sFalsef.png index 4cc53af..a971ce2 100644 --- a/data/CLs/plots/p4160_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p4160_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.31Ctt4sTruef.png b/data/CLs/plots/p4160_s/0.31Ctt4sTruef.png index aca7028..c1be5aa 100644 --- a/data/CLs/plots/p4160_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p4160_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.31Ctt5sFalsef.png b/data/CLs/plots/p4160_s/0.31Ctt5sFalsef.png index c719086..0106a62 100644 --- a/data/CLs/plots/p4160_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p4160_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.36Ctt6sTruef.png b/data/CLs/plots/p4160_s/0.36Ctt6sTruef.png index b85184a..3ee4482 100644 --- a/data/CLs/plots/p4160_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p4160_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.36Ctt7sFalsef.png b/data/CLs/plots/p4160_s/0.36Ctt7sFalsef.png index 10dfb55..4b1bb2b 100644 --- a/data/CLs/plots/p4160_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p4160_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.41Ctt8sTruef.png b/data/CLs/plots/p4160_s/0.41Ctt8sTruef.png index 68c1b37..50c457b 100644 --- a/data/CLs/plots/p4160_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p4160_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.41Ctt9sFalsef.png b/data/CLs/plots/p4160_s/0.41Ctt9sFalsef.png index 858916e..e224c1d 100644 --- a/data/CLs/plots/p4160_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p4160_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.45Ctt10sTruef.png b/data/CLs/plots/p4160_s/0.45Ctt10sTruef.png index 3ddf667..a2568f8 100644 --- a/data/CLs/plots/p4160_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p4160_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.45Ctt11sFalsef.png b/data/CLs/plots/p4160_s/0.45Ctt11sFalsef.png index 4e46bd7..4dcd374 100644 --- a/data/CLs/plots/p4160_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p4160_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.49Ctt12sTruef.png b/data/CLs/plots/p4160_s/0.49Ctt12sTruef.png index 965e037..35a0265 100644 --- a/data/CLs/plots/p4160_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p4160_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.49Ctt13sFalsef.png b/data/CLs/plots/p4160_s/0.49Ctt13sFalsef.png index a98980a..fd786ea 100644 --- a/data/CLs/plots/p4160_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p4160_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.53Ctt14sTruef.png b/data/CLs/plots/p4160_s/0.53Ctt14sTruef.png index 1552bdd..9add1fb 100644 --- a/data/CLs/plots/p4160_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p4160_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.53Ctt15sFalsef.png b/data/CLs/plots/p4160_s/0.53Ctt15sFalsef.png index b911864..e178310 100644 --- a/data/CLs/plots/p4160_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p4160_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.56Ctt16sTruef.png b/data/CLs/plots/p4160_s/0.56Ctt16sTruef.png index 23e49bd..35c53e2 100644 --- a/data/CLs/plots/p4160_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p4160_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.56Ctt17sFalsef.png b/data/CLs/plots/p4160_s/0.56Ctt17sFalsef.png index 99928b7..e70a8f1 100644 --- a/data/CLs/plots/p4160_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p4160_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.59Ctt18sTruef.png b/data/CLs/plots/p4160_s/0.59Ctt18sTruef.png index 668f9b8..2582989 100644 --- a/data/CLs/plots/p4160_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p4160_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.59Ctt19sFalsef.png b/data/CLs/plots/p4160_s/0.59Ctt19sFalsef.png index a758ce5..5cf0d9a 100644 --- a/data/CLs/plots/p4160_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p4160_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.62Ctt20sTruef.png b/data/CLs/plots/p4160_s/0.62Ctt20sTruef.png index 8a1b40d..95c1908 100644 --- a/data/CLs/plots/p4160_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p4160_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.62Ctt21sFalsef.png b/data/CLs/plots/p4160_s/0.62Ctt21sFalsef.png index da8c6d9..119e100 100644 --- a/data/CLs/plots/p4160_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p4160_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.65Ctt22sTruef.png b/data/CLs/plots/p4160_s/0.65Ctt22sTruef.png index 1ab2c91..f0f8f41 100644 --- a/data/CLs/plots/p4160_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p4160_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.65Ctt23sFalsef.png b/data/CLs/plots/p4160_s/0.65Ctt23sFalsef.png index 3d07002..b8dae29 100644 --- a/data/CLs/plots/p4160_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p4160_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.68Ctt24sTruef.png b/data/CLs/plots/p4160_s/0.68Ctt24sTruef.png index eff5327..0944630 100644 --- a/data/CLs/plots/p4160_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p4160_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.68Ctt25sFalsef.png b/data/CLs/plots/p4160_s/0.68Ctt25sFalsef.png index e151212..3dffece 100644 --- a/data/CLs/plots/p4160_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p4160_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.70Ctt26sTruef.png b/data/CLs/plots/p4160_s/0.70Ctt26sTruef.png index 3898ed8..ea41c28 100644 --- a/data/CLs/plots/p4160_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p4160_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.70Ctt27sFalsef.png b/data/CLs/plots/p4160_s/0.70Ctt27sFalsef.png index 1f9d2c7..27d0fec 100644 --- a/data/CLs/plots/p4160_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p4160_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.73Ctt28sTruef.png b/data/CLs/plots/p4160_s/0.73Ctt28sTruef.png index ec9d68b..7d34c7f 100644 --- a/data/CLs/plots/p4160_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p4160_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.73Ctt29sFalsef.png b/data/CLs/plots/p4160_s/0.73Ctt29sFalsef.png index 67e08f0..9f637ab 100644 --- a/data/CLs/plots/p4160_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p4160_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.75Ctt30sTruef.png b/data/CLs/plots/p4160_s/0.75Ctt30sTruef.png index 94459c1..0688805 100644 --- a/data/CLs/plots/p4160_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p4160_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.75Ctt31sFalsef.png b/data/CLs/plots/p4160_s/0.75Ctt31sFalsef.png index 24d9609..7841e89 100644 --- a/data/CLs/plots/p4160_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p4160_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.78Ctt32sTruef.png b/data/CLs/plots/p4160_s/0.78Ctt32sTruef.png index 79dc763..f98209d 100644 --- a/data/CLs/plots/p4160_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p4160_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.78Ctt33sFalsef.png b/data/CLs/plots/p4160_s/0.78Ctt33sFalsef.png index e02dce3..bb7dd04 100644 --- a/data/CLs/plots/p4160_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p4160_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.80Ctt34sTruef.png b/data/CLs/plots/p4160_s/0.80Ctt34sTruef.png index b6fb39b..4789b01 100644 --- a/data/CLs/plots/p4160_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p4160_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.80Ctt35sFalsef.png b/data/CLs/plots/p4160_s/0.80Ctt35sFalsef.png index 88972e3..da5dfb4 100644 --- a/data/CLs/plots/p4160_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p4160_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.82Ctt36sTruef.png b/data/CLs/plots/p4160_s/0.82Ctt36sTruef.png index 8947370..c82d0af 100644 --- a/data/CLs/plots/p4160_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p4160_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.82Ctt37sFalsef.png b/data/CLs/plots/p4160_s/0.82Ctt37sFalsef.png index 778f86b..62ca137 100644 --- a/data/CLs/plots/p4160_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p4160_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.85Ctt38sTruef.png b/data/CLs/plots/p4160_s/0.85Ctt38sTruef.png index da4f41f..7d23cce 100644 --- a/data/CLs/plots/p4160_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p4160_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p4160_s/0.85Ctt39sFalsef.png b/data/CLs/plots/p4160_s/0.85Ctt39sFalsef.png index 497979f..415ac31 100644 --- a/data/CLs/plots/p4160_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p4160_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.00Ctt0sTruef.png b/data/CLs/plots/p4415_p/0.00Ctt0sTruef.png index 4874046..ccc233b 100644 --- a/data/CLs/plots/p4415_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p4415_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.00Ctt1sFalsef.png b/data/CLs/plots/p4415_p/0.00Ctt1sFalsef.png index ba30a1a..5c8fe5e 100644 --- a/data/CLs/plots/p4415_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p4415_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.25Ctt2sTruef.png b/data/CLs/plots/p4415_p/0.25Ctt2sTruef.png index cb86cc3..e5a41c3 100644 --- a/data/CLs/plots/p4415_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p4415_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.25Ctt3sFalsef.png b/data/CLs/plots/p4415_p/0.25Ctt3sFalsef.png index e9d1ab6..f44ddbb 100644 --- a/data/CLs/plots/p4415_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p4415_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.31Ctt4sTruef.png b/data/CLs/plots/p4415_p/0.31Ctt4sTruef.png index b4ab448..dbd445f 100644 --- a/data/CLs/plots/p4415_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p4415_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.31Ctt5sFalsef.png b/data/CLs/plots/p4415_p/0.31Ctt5sFalsef.png index a81e489..ce1f3fc 100644 --- a/data/CLs/plots/p4415_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p4415_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.36Ctt6sTruef.png b/data/CLs/plots/p4415_p/0.36Ctt6sTruef.png index 815a2e3..9c6112c 100644 --- a/data/CLs/plots/p4415_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p4415_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.36Ctt7sFalsef.png b/data/CLs/plots/p4415_p/0.36Ctt7sFalsef.png index be8a054..7b7793a 100644 --- a/data/CLs/plots/p4415_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p4415_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.41Ctt8sTruef.png b/data/CLs/plots/p4415_p/0.41Ctt8sTruef.png index 5e50890..b6b0ca1 100644 --- a/data/CLs/plots/p4415_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p4415_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.41Ctt9sFalsef.png b/data/CLs/plots/p4415_p/0.41Ctt9sFalsef.png index 4cd62a5..65e7291 100644 --- a/data/CLs/plots/p4415_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p4415_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.45Ctt10sTruef.png b/data/CLs/plots/p4415_p/0.45Ctt10sTruef.png index 85f56cb..8e17aed 100644 --- a/data/CLs/plots/p4415_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p4415_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.45Ctt11sFalsef.png b/data/CLs/plots/p4415_p/0.45Ctt11sFalsef.png index a814161..f58326c 100644 --- a/data/CLs/plots/p4415_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p4415_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.49Ctt12sTruef.png b/data/CLs/plots/p4415_p/0.49Ctt12sTruef.png index 6bc0c94..b916210 100644 --- a/data/CLs/plots/p4415_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p4415_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.49Ctt13sFalsef.png b/data/CLs/plots/p4415_p/0.49Ctt13sFalsef.png index ea6a60d..29c8178 100644 --- a/data/CLs/plots/p4415_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p4415_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.53Ctt14sTruef.png b/data/CLs/plots/p4415_p/0.53Ctt14sTruef.png index 7ef8bc7..3359839 100644 --- a/data/CLs/plots/p4415_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p4415_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.53Ctt15sFalsef.png b/data/CLs/plots/p4415_p/0.53Ctt15sFalsef.png index 30df51c..d2ab60c 100644 --- a/data/CLs/plots/p4415_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p4415_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.56Ctt16sTruef.png b/data/CLs/plots/p4415_p/0.56Ctt16sTruef.png index 3374c7d..09d1137 100644 --- a/data/CLs/plots/p4415_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p4415_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.56Ctt17sFalsef.png b/data/CLs/plots/p4415_p/0.56Ctt17sFalsef.png index 8e56ee2..a9af412 100644 --- a/data/CLs/plots/p4415_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p4415_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.59Ctt18sTruef.png b/data/CLs/plots/p4415_p/0.59Ctt18sTruef.png index 8b133bd..fc439da 100644 --- a/data/CLs/plots/p4415_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p4415_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.59Ctt19sFalsef.png b/data/CLs/plots/p4415_p/0.59Ctt19sFalsef.png index 075927a..35a21f3 100644 --- a/data/CLs/plots/p4415_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p4415_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.62Ctt20sTruef.png b/data/CLs/plots/p4415_p/0.62Ctt20sTruef.png index 27ea1ed..852ee3d 100644 --- a/data/CLs/plots/p4415_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p4415_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.62Ctt21sFalsef.png b/data/CLs/plots/p4415_p/0.62Ctt21sFalsef.png index 5cd33dd..795d36e 100644 --- a/data/CLs/plots/p4415_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p4415_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.65Ctt22sTruef.png b/data/CLs/plots/p4415_p/0.65Ctt22sTruef.png index 42be023..f626244 100644 --- a/data/CLs/plots/p4415_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p4415_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.65Ctt23sFalsef.png b/data/CLs/plots/p4415_p/0.65Ctt23sFalsef.png index 96eba01..fbf0124 100644 --- a/data/CLs/plots/p4415_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p4415_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.68Ctt24sTruef.png b/data/CLs/plots/p4415_p/0.68Ctt24sTruef.png index 8494dbd..7f60995 100644 --- a/data/CLs/plots/p4415_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p4415_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.68Ctt25sFalsef.png b/data/CLs/plots/p4415_p/0.68Ctt25sFalsef.png index 149bf24..5c88c77 100644 --- a/data/CLs/plots/p4415_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p4415_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.70Ctt26sTruef.png b/data/CLs/plots/p4415_p/0.70Ctt26sTruef.png index a49d694..fb1296f 100644 --- a/data/CLs/plots/p4415_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p4415_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.70Ctt27sFalsef.png b/data/CLs/plots/p4415_p/0.70Ctt27sFalsef.png index f05becb..b25db1b 100644 --- a/data/CLs/plots/p4415_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p4415_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.73Ctt28sTruef.png b/data/CLs/plots/p4415_p/0.73Ctt28sTruef.png index 04ee54e..ab98b1b 100644 --- a/data/CLs/plots/p4415_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p4415_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.73Ctt29sFalsef.png b/data/CLs/plots/p4415_p/0.73Ctt29sFalsef.png index 814665c..5b16684 100644 --- a/data/CLs/plots/p4415_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p4415_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.75Ctt30sTruef.png b/data/CLs/plots/p4415_p/0.75Ctt30sTruef.png index f793a90..ea0bd12 100644 --- a/data/CLs/plots/p4415_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p4415_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.75Ctt31sFalsef.png b/data/CLs/plots/p4415_p/0.75Ctt31sFalsef.png index b0ee220..b8aebbf 100644 --- a/data/CLs/plots/p4415_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p4415_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.78Ctt32sTruef.png b/data/CLs/plots/p4415_p/0.78Ctt32sTruef.png index d9e68cc..72ad186 100644 --- a/data/CLs/plots/p4415_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p4415_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.78Ctt33sFalsef.png b/data/CLs/plots/p4415_p/0.78Ctt33sFalsef.png index b434b03..b4652d4 100644 --- a/data/CLs/plots/p4415_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p4415_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.80Ctt34sTruef.png b/data/CLs/plots/p4415_p/0.80Ctt34sTruef.png index 4cd5465..afcee7b 100644 --- a/data/CLs/plots/p4415_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p4415_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.80Ctt35sFalsef.png b/data/CLs/plots/p4415_p/0.80Ctt35sFalsef.png index 2702d73..0b6e216 100644 --- a/data/CLs/plots/p4415_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p4415_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.82Ctt36sTruef.png b/data/CLs/plots/p4415_p/0.82Ctt36sTruef.png index 0906f4f..bd3199d 100644 --- a/data/CLs/plots/p4415_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p4415_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.82Ctt37sFalsef.png b/data/CLs/plots/p4415_p/0.82Ctt37sFalsef.png index 749521b..086e337 100644 --- a/data/CLs/plots/p4415_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p4415_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.85Ctt38sTruef.png b/data/CLs/plots/p4415_p/0.85Ctt38sTruef.png index 24117db..ab42933 100644 --- a/data/CLs/plots/p4415_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p4415_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_p/0.85Ctt39sFalsef.png b/data/CLs/plots/p4415_p/0.85Ctt39sFalsef.png index 07e2528..e996940 100644 --- a/data/CLs/plots/p4415_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p4415_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.00Ctt0sTruef.png b/data/CLs/plots/p4415_s/0.00Ctt0sTruef.png index f7c4f5f..297e5f3 100644 --- a/data/CLs/plots/p4415_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/p4415_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.00Ctt1sFalsef.png b/data/CLs/plots/p4415_s/0.00Ctt1sFalsef.png index a5b13e0..24da936 100644 --- a/data/CLs/plots/p4415_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/p4415_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.25Ctt2sTruef.png b/data/CLs/plots/p4415_s/0.25Ctt2sTruef.png index 6d2acf5..b10ba0a 100644 --- a/data/CLs/plots/p4415_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/p4415_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.25Ctt3sFalsef.png b/data/CLs/plots/p4415_s/0.25Ctt3sFalsef.png index 12e41a1..0affe9a 100644 --- a/data/CLs/plots/p4415_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/p4415_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.31Ctt4sTruef.png b/data/CLs/plots/p4415_s/0.31Ctt4sTruef.png index d5f30b4..f0714ab 100644 --- a/data/CLs/plots/p4415_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/p4415_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.31Ctt5sFalsef.png b/data/CLs/plots/p4415_s/0.31Ctt5sFalsef.png index 5f72d4e..fcd3059 100644 --- a/data/CLs/plots/p4415_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/p4415_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.36Ctt6sTruef.png b/data/CLs/plots/p4415_s/0.36Ctt6sTruef.png index bb2fae1..43f1595 100644 --- a/data/CLs/plots/p4415_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/p4415_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.36Ctt7sFalsef.png b/data/CLs/plots/p4415_s/0.36Ctt7sFalsef.png index d3cdf82..627a067 100644 --- a/data/CLs/plots/p4415_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/p4415_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.41Ctt8sTruef.png b/data/CLs/plots/p4415_s/0.41Ctt8sTruef.png index 1a00513..4f1b975 100644 --- a/data/CLs/plots/p4415_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/p4415_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.41Ctt9sFalsef.png b/data/CLs/plots/p4415_s/0.41Ctt9sFalsef.png index e385951..8d6bf0b 100644 --- a/data/CLs/plots/p4415_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/p4415_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.45Ctt10sTruef.png b/data/CLs/plots/p4415_s/0.45Ctt10sTruef.png index 240d515..e686511 100644 --- a/data/CLs/plots/p4415_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/p4415_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.45Ctt11sFalsef.png b/data/CLs/plots/p4415_s/0.45Ctt11sFalsef.png index 7793e9b..3add5be 100644 --- a/data/CLs/plots/p4415_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/p4415_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.49Ctt12sTruef.png b/data/CLs/plots/p4415_s/0.49Ctt12sTruef.png index 8c76150..a939074 100644 --- a/data/CLs/plots/p4415_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/p4415_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.49Ctt13sFalsef.png b/data/CLs/plots/p4415_s/0.49Ctt13sFalsef.png index 6fd3b78..c94283e 100644 --- a/data/CLs/plots/p4415_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/p4415_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.53Ctt14sTruef.png b/data/CLs/plots/p4415_s/0.53Ctt14sTruef.png index b40253f..fde8858 100644 --- a/data/CLs/plots/p4415_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/p4415_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.53Ctt15sFalsef.png b/data/CLs/plots/p4415_s/0.53Ctt15sFalsef.png index f93c39d..fa8e9a9 100644 --- a/data/CLs/plots/p4415_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/p4415_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.56Ctt16sTruef.png b/data/CLs/plots/p4415_s/0.56Ctt16sTruef.png index 93664d7..4100e1c 100644 --- a/data/CLs/plots/p4415_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/p4415_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.56Ctt17sFalsef.png b/data/CLs/plots/p4415_s/0.56Ctt17sFalsef.png index cf3be80..52661a0 100644 --- a/data/CLs/plots/p4415_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/p4415_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.59Ctt18sTruef.png b/data/CLs/plots/p4415_s/0.59Ctt18sTruef.png index 1c44e7d..f5c1598 100644 --- a/data/CLs/plots/p4415_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/p4415_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.59Ctt19sFalsef.png b/data/CLs/plots/p4415_s/0.59Ctt19sFalsef.png index 36b9b54..2b80779 100644 --- a/data/CLs/plots/p4415_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/p4415_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.62Ctt20sTruef.png b/data/CLs/plots/p4415_s/0.62Ctt20sTruef.png index 1e65bac..d8e008b 100644 --- a/data/CLs/plots/p4415_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/p4415_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.62Ctt21sFalsef.png b/data/CLs/plots/p4415_s/0.62Ctt21sFalsef.png index 25a05b8..d368820 100644 --- a/data/CLs/plots/p4415_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/p4415_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.65Ctt22sTruef.png b/data/CLs/plots/p4415_s/0.65Ctt22sTruef.png index 540fa6e..fcac317 100644 --- a/data/CLs/plots/p4415_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/p4415_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.65Ctt23sFalsef.png b/data/CLs/plots/p4415_s/0.65Ctt23sFalsef.png index 768c1b1..61b0b26 100644 --- a/data/CLs/plots/p4415_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/p4415_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.68Ctt24sTruef.png b/data/CLs/plots/p4415_s/0.68Ctt24sTruef.png index 3ab18a7..b10f6e2 100644 --- a/data/CLs/plots/p4415_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/p4415_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.68Ctt25sFalsef.png b/data/CLs/plots/p4415_s/0.68Ctt25sFalsef.png index a01e634..7a0f2f7 100644 --- a/data/CLs/plots/p4415_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/p4415_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.70Ctt26sTruef.png b/data/CLs/plots/p4415_s/0.70Ctt26sTruef.png index 3bad2b9..a2cf64f 100644 --- a/data/CLs/plots/p4415_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/p4415_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.70Ctt27sFalsef.png b/data/CLs/plots/p4415_s/0.70Ctt27sFalsef.png index 96eb71d..0a35fb9 100644 --- a/data/CLs/plots/p4415_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/p4415_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.73Ctt28sTruef.png b/data/CLs/plots/p4415_s/0.73Ctt28sTruef.png index c816aaf..0a4b809 100644 --- a/data/CLs/plots/p4415_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/p4415_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.73Ctt29sFalsef.png b/data/CLs/plots/p4415_s/0.73Ctt29sFalsef.png index 3541957..5cf1791 100644 --- a/data/CLs/plots/p4415_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/p4415_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.75Ctt30sTruef.png b/data/CLs/plots/p4415_s/0.75Ctt30sTruef.png index 73737f8..03520a1 100644 --- a/data/CLs/plots/p4415_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/p4415_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.75Ctt31sFalsef.png b/data/CLs/plots/p4415_s/0.75Ctt31sFalsef.png index 15ae81d..22d60e2 100644 --- a/data/CLs/plots/p4415_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/p4415_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.78Ctt32sTruef.png b/data/CLs/plots/p4415_s/0.78Ctt32sTruef.png index 9e06a3f..8a5aaa4 100644 --- a/data/CLs/plots/p4415_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/p4415_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.78Ctt33sFalsef.png b/data/CLs/plots/p4415_s/0.78Ctt33sFalsef.png index 923c928..fa3a372 100644 --- a/data/CLs/plots/p4415_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/p4415_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.80Ctt34sTruef.png b/data/CLs/plots/p4415_s/0.80Ctt34sTruef.png index d490be7..0703a6a 100644 --- a/data/CLs/plots/p4415_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/p4415_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.80Ctt35sFalsef.png b/data/CLs/plots/p4415_s/0.80Ctt35sFalsef.png index b10a1da..801f8dd 100644 --- a/data/CLs/plots/p4415_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/p4415_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.82Ctt36sTruef.png b/data/CLs/plots/p4415_s/0.82Ctt36sTruef.png index a57e2d2..e034276 100644 --- a/data/CLs/plots/p4415_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/p4415_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.82Ctt37sFalsef.png b/data/CLs/plots/p4415_s/0.82Ctt37sFalsef.png index b9697d2..f809033 100644 --- a/data/CLs/plots/p4415_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/p4415_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.85Ctt38sTruef.png b/data/CLs/plots/p4415_s/0.85Ctt38sTruef.png index 7bc5ad0..07e85fb 100644 --- a/data/CLs/plots/p4415_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/p4415_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/p4415_s/0.85Ctt39sFalsef.png b/data/CLs/plots/p4415_s/0.85Ctt39sFalsef.png index cff8598..3ea4c12 100644 --- a/data/CLs/plots/p4415_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/p4415_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.00Ctt0sTruef.png b/data/CLs/plots/phi_p/0.00Ctt0sTruef.png index ab2e078..b4ee122 100644 --- a/data/CLs/plots/phi_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/phi_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.00Ctt1sFalsef.png b/data/CLs/plots/phi_p/0.00Ctt1sFalsef.png index c6026f6..255a61c 100644 --- a/data/CLs/plots/phi_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/phi_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.25Ctt2sTruef.png b/data/CLs/plots/phi_p/0.25Ctt2sTruef.png index 7236570..dfcfcc8 100644 --- a/data/CLs/plots/phi_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/phi_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.25Ctt3sFalsef.png b/data/CLs/plots/phi_p/0.25Ctt3sFalsef.png index fcdf842..1f46f28 100644 --- a/data/CLs/plots/phi_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/phi_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.31Ctt4sTruef.png b/data/CLs/plots/phi_p/0.31Ctt4sTruef.png index 298771a..f9ca81d 100644 --- a/data/CLs/plots/phi_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/phi_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.31Ctt5sFalsef.png b/data/CLs/plots/phi_p/0.31Ctt5sFalsef.png index d6d2c81..0096a2c 100644 --- a/data/CLs/plots/phi_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/phi_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.36Ctt6sTruef.png b/data/CLs/plots/phi_p/0.36Ctt6sTruef.png index 988e147..33bb4f2 100644 --- a/data/CLs/plots/phi_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/phi_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.36Ctt7sFalsef.png b/data/CLs/plots/phi_p/0.36Ctt7sFalsef.png index 74e329a..5b5f841 100644 --- a/data/CLs/plots/phi_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/phi_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.41Ctt8sTruef.png b/data/CLs/plots/phi_p/0.41Ctt8sTruef.png index 2496158..2af57ea 100644 --- a/data/CLs/plots/phi_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/phi_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.41Ctt9sFalsef.png b/data/CLs/plots/phi_p/0.41Ctt9sFalsef.png index 17adc2c..9bc238d 100644 --- a/data/CLs/plots/phi_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/phi_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.45Ctt10sTruef.png b/data/CLs/plots/phi_p/0.45Ctt10sTruef.png index 96109d3..f75c102 100644 --- a/data/CLs/plots/phi_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/phi_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.45Ctt11sFalsef.png b/data/CLs/plots/phi_p/0.45Ctt11sFalsef.png index 33e4eaf..bd3a2ee 100644 --- a/data/CLs/plots/phi_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/phi_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.49Ctt12sTruef.png b/data/CLs/plots/phi_p/0.49Ctt12sTruef.png index bbbc8ec..300b73d 100644 --- a/data/CLs/plots/phi_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/phi_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.49Ctt13sFalsef.png b/data/CLs/plots/phi_p/0.49Ctt13sFalsef.png index 44dc8e9..ad36d82 100644 --- a/data/CLs/plots/phi_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/phi_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.53Ctt14sTruef.png b/data/CLs/plots/phi_p/0.53Ctt14sTruef.png index 6832026..e38fcc3 100644 --- a/data/CLs/plots/phi_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/phi_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.53Ctt15sFalsef.png b/data/CLs/plots/phi_p/0.53Ctt15sFalsef.png index a3811e5..e38ed98 100644 --- a/data/CLs/plots/phi_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/phi_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.56Ctt16sTruef.png b/data/CLs/plots/phi_p/0.56Ctt16sTruef.png index 3b7de6c..2139e8d 100644 --- a/data/CLs/plots/phi_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/phi_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.56Ctt17sFalsef.png b/data/CLs/plots/phi_p/0.56Ctt17sFalsef.png index 184e18f..5fa9d53 100644 --- a/data/CLs/plots/phi_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/phi_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.59Ctt18sTruef.png b/data/CLs/plots/phi_p/0.59Ctt18sTruef.png index 55d82a0..d34d6c0 100644 --- a/data/CLs/plots/phi_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/phi_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.59Ctt19sFalsef.png b/data/CLs/plots/phi_p/0.59Ctt19sFalsef.png index 3e4f1d2..3fb0e89 100644 --- a/data/CLs/plots/phi_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/phi_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.62Ctt20sTruef.png b/data/CLs/plots/phi_p/0.62Ctt20sTruef.png index db9dbe8..83e47ce 100644 --- a/data/CLs/plots/phi_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/phi_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.62Ctt21sFalsef.png b/data/CLs/plots/phi_p/0.62Ctt21sFalsef.png index 0ec20f1..fa43270 100644 --- a/data/CLs/plots/phi_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/phi_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.65Ctt22sTruef.png b/data/CLs/plots/phi_p/0.65Ctt22sTruef.png index 9d10b4e..c8c61ea 100644 --- a/data/CLs/plots/phi_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/phi_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.65Ctt23sFalsef.png b/data/CLs/plots/phi_p/0.65Ctt23sFalsef.png index ab70139..745a994 100644 --- a/data/CLs/plots/phi_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/phi_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.68Ctt24sTruef.png b/data/CLs/plots/phi_p/0.68Ctt24sTruef.png index 3375d53..7685255 100644 --- a/data/CLs/plots/phi_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/phi_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.68Ctt25sFalsef.png b/data/CLs/plots/phi_p/0.68Ctt25sFalsef.png index 58f9caa..e35f6fc 100644 --- a/data/CLs/plots/phi_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/phi_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.70Ctt26sTruef.png b/data/CLs/plots/phi_p/0.70Ctt26sTruef.png index 8ab03a5..ab59322 100644 --- a/data/CLs/plots/phi_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/phi_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.70Ctt27sFalsef.png b/data/CLs/plots/phi_p/0.70Ctt27sFalsef.png index cdd7d52..e938223 100644 --- a/data/CLs/plots/phi_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/phi_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.73Ctt28sTruef.png b/data/CLs/plots/phi_p/0.73Ctt28sTruef.png index 68c4e9e..5753790 100644 --- a/data/CLs/plots/phi_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/phi_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.73Ctt29sFalsef.png b/data/CLs/plots/phi_p/0.73Ctt29sFalsef.png index c0a3056..38a54dd 100644 --- a/data/CLs/plots/phi_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/phi_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.75Ctt30sTruef.png b/data/CLs/plots/phi_p/0.75Ctt30sTruef.png index 1590d29..dcbdba0 100644 --- a/data/CLs/plots/phi_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/phi_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.75Ctt31sFalsef.png b/data/CLs/plots/phi_p/0.75Ctt31sFalsef.png index ee89228..aac287b 100644 --- a/data/CLs/plots/phi_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/phi_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.78Ctt32sTruef.png b/data/CLs/plots/phi_p/0.78Ctt32sTruef.png index f795f7c..638a72d 100644 --- a/data/CLs/plots/phi_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/phi_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.78Ctt33sFalsef.png b/data/CLs/plots/phi_p/0.78Ctt33sFalsef.png index fe57747..a369720 100644 --- a/data/CLs/plots/phi_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/phi_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.80Ctt34sTruef.png b/data/CLs/plots/phi_p/0.80Ctt34sTruef.png index 9f0cc1c..1cd2649 100644 --- a/data/CLs/plots/phi_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/phi_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.80Ctt35sFalsef.png b/data/CLs/plots/phi_p/0.80Ctt35sFalsef.png index fdbfb92..113af93 100644 --- a/data/CLs/plots/phi_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/phi_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.82Ctt36sTruef.png b/data/CLs/plots/phi_p/0.82Ctt36sTruef.png index c1469a6..dc84d56 100644 --- a/data/CLs/plots/phi_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/phi_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.82Ctt37sFalsef.png b/data/CLs/plots/phi_p/0.82Ctt37sFalsef.png index d302a03..8ae2f7a 100644 --- a/data/CLs/plots/phi_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/phi_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.85Ctt38sTruef.png b/data/CLs/plots/phi_p/0.85Ctt38sTruef.png index 4786dbe..e68bbd6 100644 --- a/data/CLs/plots/phi_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/phi_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_p/0.85Ctt39sFalsef.png b/data/CLs/plots/phi_p/0.85Ctt39sFalsef.png index 0de26e2..0711017 100644 --- a/data/CLs/plots/phi_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/phi_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.00Ctt0sTruef.png b/data/CLs/plots/phi_s/0.00Ctt0sTruef.png index 10bcde9..2de6d7b 100644 --- a/data/CLs/plots/phi_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/phi_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.00Ctt1sFalsef.png b/data/CLs/plots/phi_s/0.00Ctt1sFalsef.png index 4200ecf..bc562b7 100644 --- a/data/CLs/plots/phi_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/phi_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.25Ctt2sTruef.png b/data/CLs/plots/phi_s/0.25Ctt2sTruef.png index 2ad128c..fd92c1f 100644 --- a/data/CLs/plots/phi_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/phi_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.25Ctt3sFalsef.png b/data/CLs/plots/phi_s/0.25Ctt3sFalsef.png index d0299b6..8e5fe90 100644 --- a/data/CLs/plots/phi_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/phi_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.31Ctt4sTruef.png b/data/CLs/plots/phi_s/0.31Ctt4sTruef.png index 122cf1e..f9f0068 100644 --- a/data/CLs/plots/phi_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/phi_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.31Ctt5sFalsef.png b/data/CLs/plots/phi_s/0.31Ctt5sFalsef.png index 97ce1e5..7798c3d 100644 --- a/data/CLs/plots/phi_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/phi_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.36Ctt6sTruef.png b/data/CLs/plots/phi_s/0.36Ctt6sTruef.png index 0f0b44a..1380e75 100644 --- a/data/CLs/plots/phi_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/phi_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.36Ctt7sFalsef.png b/data/CLs/plots/phi_s/0.36Ctt7sFalsef.png index 5d9b2ba..ffa3d6f 100644 --- a/data/CLs/plots/phi_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/phi_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.41Ctt8sTruef.png b/data/CLs/plots/phi_s/0.41Ctt8sTruef.png index b57e0d3..cb3b99f 100644 --- a/data/CLs/plots/phi_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/phi_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.41Ctt9sFalsef.png b/data/CLs/plots/phi_s/0.41Ctt9sFalsef.png index a6c7eef..695822f 100644 --- a/data/CLs/plots/phi_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/phi_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.45Ctt10sTruef.png b/data/CLs/plots/phi_s/0.45Ctt10sTruef.png index 735e2bb..fea5518 100644 --- a/data/CLs/plots/phi_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/phi_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.45Ctt11sFalsef.png b/data/CLs/plots/phi_s/0.45Ctt11sFalsef.png index 0942d9a..ba9a6ec 100644 --- a/data/CLs/plots/phi_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/phi_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.49Ctt12sTruef.png b/data/CLs/plots/phi_s/0.49Ctt12sTruef.png index 0947e2e..3ca207e 100644 --- a/data/CLs/plots/phi_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/phi_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.49Ctt13sFalsef.png b/data/CLs/plots/phi_s/0.49Ctt13sFalsef.png index 8dfc260..080074c 100644 --- a/data/CLs/plots/phi_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/phi_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.53Ctt14sTruef.png b/data/CLs/plots/phi_s/0.53Ctt14sTruef.png index 5d3a6d1..9482da4 100644 --- a/data/CLs/plots/phi_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/phi_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.53Ctt15sFalsef.png b/data/CLs/plots/phi_s/0.53Ctt15sFalsef.png index 7d2e79f..560c6b9 100644 --- a/data/CLs/plots/phi_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/phi_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.56Ctt16sTruef.png b/data/CLs/plots/phi_s/0.56Ctt16sTruef.png index 4856358..96530c7 100644 --- a/data/CLs/plots/phi_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/phi_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.56Ctt17sFalsef.png b/data/CLs/plots/phi_s/0.56Ctt17sFalsef.png index 0fdb914..08e8840 100644 --- a/data/CLs/plots/phi_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/phi_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.59Ctt18sTruef.png b/data/CLs/plots/phi_s/0.59Ctt18sTruef.png index e78681a..2db01a8 100644 --- a/data/CLs/plots/phi_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/phi_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.59Ctt19sFalsef.png b/data/CLs/plots/phi_s/0.59Ctt19sFalsef.png index 984f6f7..cf10710 100644 --- a/data/CLs/plots/phi_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/phi_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.62Ctt20sTruef.png b/data/CLs/plots/phi_s/0.62Ctt20sTruef.png index c8f1b36..a1b5acf 100644 --- a/data/CLs/plots/phi_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/phi_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.62Ctt21sFalsef.png b/data/CLs/plots/phi_s/0.62Ctt21sFalsef.png index 78783bd..4c3c34e 100644 --- a/data/CLs/plots/phi_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/phi_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.65Ctt22sTruef.png b/data/CLs/plots/phi_s/0.65Ctt22sTruef.png index 5f39f51..bce9e54 100644 --- a/data/CLs/plots/phi_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/phi_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.65Ctt23sFalsef.png b/data/CLs/plots/phi_s/0.65Ctt23sFalsef.png index 6155cf6..28cf477 100644 --- a/data/CLs/plots/phi_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/phi_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.68Ctt24sTruef.png b/data/CLs/plots/phi_s/0.68Ctt24sTruef.png index f2b50da..3429e17 100644 --- a/data/CLs/plots/phi_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/phi_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.68Ctt25sFalsef.png b/data/CLs/plots/phi_s/0.68Ctt25sFalsef.png index 9bda2cc..4d7a0d4 100644 --- a/data/CLs/plots/phi_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/phi_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.70Ctt26sTruef.png b/data/CLs/plots/phi_s/0.70Ctt26sTruef.png index 38a2490..a3f2d38 100644 --- a/data/CLs/plots/phi_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/phi_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.70Ctt27sFalsef.png b/data/CLs/plots/phi_s/0.70Ctt27sFalsef.png index a18a483..681a454 100644 --- a/data/CLs/plots/phi_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/phi_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.73Ctt28sTruef.png b/data/CLs/plots/phi_s/0.73Ctt28sTruef.png index 1013e0f..22150b8 100644 --- a/data/CLs/plots/phi_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/phi_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.73Ctt29sFalsef.png b/data/CLs/plots/phi_s/0.73Ctt29sFalsef.png index 42ffd8c..8691e13 100644 --- a/data/CLs/plots/phi_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/phi_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.75Ctt30sTruef.png b/data/CLs/plots/phi_s/0.75Ctt30sTruef.png index fecb1d6..d976de2 100644 --- a/data/CLs/plots/phi_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/phi_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.75Ctt31sFalsef.png b/data/CLs/plots/phi_s/0.75Ctt31sFalsef.png index 79a46a4..31dbbba 100644 --- a/data/CLs/plots/phi_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/phi_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.78Ctt32sTruef.png b/data/CLs/plots/phi_s/0.78Ctt32sTruef.png index 7874991..3e5675d 100644 --- a/data/CLs/plots/phi_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/phi_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.78Ctt33sFalsef.png b/data/CLs/plots/phi_s/0.78Ctt33sFalsef.png index 24ab6de..dda25c0 100644 --- a/data/CLs/plots/phi_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/phi_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.80Ctt34sTruef.png b/data/CLs/plots/phi_s/0.80Ctt34sTruef.png index fecc1d2..5d47b10 100644 --- a/data/CLs/plots/phi_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/phi_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.80Ctt35sFalsef.png b/data/CLs/plots/phi_s/0.80Ctt35sFalsef.png index 394a038..4013ad2 100644 --- a/data/CLs/plots/phi_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/phi_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.82Ctt36sTruef.png b/data/CLs/plots/phi_s/0.82Ctt36sTruef.png index c02d119..7d0038c 100644 --- a/data/CLs/plots/phi_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/phi_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.82Ctt37sFalsef.png b/data/CLs/plots/phi_s/0.82Ctt37sFalsef.png index 55f2b64..5df31a2 100644 --- a/data/CLs/plots/phi_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/phi_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.85Ctt38sTruef.png b/data/CLs/plots/phi_s/0.85Ctt38sTruef.png index 2166841..2be177c 100644 --- a/data/CLs/plots/phi_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/phi_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/phi_s/0.85Ctt39sFalsef.png b/data/CLs/plots/phi_s/0.85Ctt39sFalsef.png index d7ec3bc..7bbf1ed 100644 --- a/data/CLs/plots/phi_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/phi_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.00Ctt0sTruef.png b/data/CLs/plots/psi2s_p/0.00Ctt0sTruef.png index e73683a..79bcb75 100644 --- a/data/CLs/plots/psi2s_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/psi2s_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.00Ctt1sFalsef.png b/data/CLs/plots/psi2s_p/0.00Ctt1sFalsef.png index 162073b..a323fca 100644 --- a/data/CLs/plots/psi2s_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.25Ctt2sTruef.png b/data/CLs/plots/psi2s_p/0.25Ctt2sTruef.png index aaf41ad..d670320 100644 --- a/data/CLs/plots/psi2s_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/psi2s_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.25Ctt3sFalsef.png b/data/CLs/plots/psi2s_p/0.25Ctt3sFalsef.png index 7e25227..981a464 100644 --- a/data/CLs/plots/psi2s_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.31Ctt4sTruef.png b/data/CLs/plots/psi2s_p/0.31Ctt4sTruef.png index 2d63b6f..2e479eb 100644 --- a/data/CLs/plots/psi2s_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/psi2s_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.31Ctt5sFalsef.png b/data/CLs/plots/psi2s_p/0.31Ctt5sFalsef.png index cfc8254..63c77f0 100644 --- a/data/CLs/plots/psi2s_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.36Ctt6sTruef.png b/data/CLs/plots/psi2s_p/0.36Ctt6sTruef.png index 73d0906..fcbb910 100644 --- a/data/CLs/plots/psi2s_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/psi2s_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.36Ctt7sFalsef.png b/data/CLs/plots/psi2s_p/0.36Ctt7sFalsef.png index cd00f06..43e82be 100644 --- a/data/CLs/plots/psi2s_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.41Ctt8sTruef.png b/data/CLs/plots/psi2s_p/0.41Ctt8sTruef.png index 00e05bf..b0fa0f3 100644 --- a/data/CLs/plots/psi2s_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/psi2s_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.41Ctt9sFalsef.png b/data/CLs/plots/psi2s_p/0.41Ctt9sFalsef.png index 63aa8a9..1b65e69 100644 --- a/data/CLs/plots/psi2s_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.45Ctt10sTruef.png b/data/CLs/plots/psi2s_p/0.45Ctt10sTruef.png index 1f00df5..fed655f 100644 --- a/data/CLs/plots/psi2s_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/psi2s_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.45Ctt11sFalsef.png b/data/CLs/plots/psi2s_p/0.45Ctt11sFalsef.png index 7863482..847ae24 100644 --- a/data/CLs/plots/psi2s_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.49Ctt12sTruef.png b/data/CLs/plots/psi2s_p/0.49Ctt12sTruef.png index 15006c2..bb0a3d5 100644 --- a/data/CLs/plots/psi2s_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/psi2s_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.49Ctt13sFalsef.png b/data/CLs/plots/psi2s_p/0.49Ctt13sFalsef.png index 09c899b..4489e8a 100644 --- a/data/CLs/plots/psi2s_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.53Ctt14sTruef.png b/data/CLs/plots/psi2s_p/0.53Ctt14sTruef.png index a45af25..1dd466c 100644 --- a/data/CLs/plots/psi2s_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/psi2s_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.53Ctt15sFalsef.png b/data/CLs/plots/psi2s_p/0.53Ctt15sFalsef.png index 4bda78c..18fdd35 100644 --- a/data/CLs/plots/psi2s_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.56Ctt16sTruef.png b/data/CLs/plots/psi2s_p/0.56Ctt16sTruef.png index e7cecf4..d15180c 100644 --- a/data/CLs/plots/psi2s_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/psi2s_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.56Ctt17sFalsef.png b/data/CLs/plots/psi2s_p/0.56Ctt17sFalsef.png index 7cb791b..b4406c1 100644 --- a/data/CLs/plots/psi2s_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.59Ctt18sTruef.png b/data/CLs/plots/psi2s_p/0.59Ctt18sTruef.png index e85768c..2e57931 100644 --- a/data/CLs/plots/psi2s_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/psi2s_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.59Ctt19sFalsef.png b/data/CLs/plots/psi2s_p/0.59Ctt19sFalsef.png index 1debb6c..6163356 100644 --- a/data/CLs/plots/psi2s_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.62Ctt20sTruef.png b/data/CLs/plots/psi2s_p/0.62Ctt20sTruef.png index 4656182..6dfb0db 100644 --- a/data/CLs/plots/psi2s_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/psi2s_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.62Ctt21sFalsef.png b/data/CLs/plots/psi2s_p/0.62Ctt21sFalsef.png index a9cf16e..4d43abb 100644 --- a/data/CLs/plots/psi2s_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.65Ctt22sTruef.png b/data/CLs/plots/psi2s_p/0.65Ctt22sTruef.png index 2501656..0460021 100644 --- a/data/CLs/plots/psi2s_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/psi2s_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.65Ctt23sFalsef.png b/data/CLs/plots/psi2s_p/0.65Ctt23sFalsef.png index ffd1672..97f8163 100644 --- a/data/CLs/plots/psi2s_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.68Ctt24sTruef.png b/data/CLs/plots/psi2s_p/0.68Ctt24sTruef.png index 151dcac..c7d4651 100644 --- a/data/CLs/plots/psi2s_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/psi2s_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.68Ctt25sFalsef.png b/data/CLs/plots/psi2s_p/0.68Ctt25sFalsef.png index 35373ea..6754a83 100644 --- a/data/CLs/plots/psi2s_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.70Ctt26sTruef.png b/data/CLs/plots/psi2s_p/0.70Ctt26sTruef.png index 146bb81..8d453a4 100644 --- a/data/CLs/plots/psi2s_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/psi2s_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.70Ctt27sFalsef.png b/data/CLs/plots/psi2s_p/0.70Ctt27sFalsef.png index 49bf3eb..7825024 100644 --- a/data/CLs/plots/psi2s_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.73Ctt28sTruef.png b/data/CLs/plots/psi2s_p/0.73Ctt28sTruef.png index 6f92707..1ff980e 100644 --- a/data/CLs/plots/psi2s_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/psi2s_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.73Ctt29sFalsef.png b/data/CLs/plots/psi2s_p/0.73Ctt29sFalsef.png index 35ca5a9..e8b1041 100644 --- a/data/CLs/plots/psi2s_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.75Ctt30sTruef.png b/data/CLs/plots/psi2s_p/0.75Ctt30sTruef.png index 5dd387a..9b77375 100644 --- a/data/CLs/plots/psi2s_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/psi2s_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.75Ctt31sFalsef.png b/data/CLs/plots/psi2s_p/0.75Ctt31sFalsef.png index 539500c..09df297 100644 --- a/data/CLs/plots/psi2s_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.78Ctt32sTruef.png b/data/CLs/plots/psi2s_p/0.78Ctt32sTruef.png index 8a00bbf..d9ae897 100644 --- a/data/CLs/plots/psi2s_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/psi2s_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.78Ctt33sFalsef.png b/data/CLs/plots/psi2s_p/0.78Ctt33sFalsef.png index 9040818..5ad3849 100644 --- a/data/CLs/plots/psi2s_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.80Ctt34sTruef.png b/data/CLs/plots/psi2s_p/0.80Ctt34sTruef.png index 8b6604b..9ce1815 100644 --- a/data/CLs/plots/psi2s_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/psi2s_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.80Ctt35sFalsef.png b/data/CLs/plots/psi2s_p/0.80Ctt35sFalsef.png index 8102226..ab8a28b 100644 --- a/data/CLs/plots/psi2s_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.82Ctt36sTruef.png b/data/CLs/plots/psi2s_p/0.82Ctt36sTruef.png index 43c77e7..1e800d7 100644 --- a/data/CLs/plots/psi2s_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/psi2s_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.82Ctt37sFalsef.png b/data/CLs/plots/psi2s_p/0.82Ctt37sFalsef.png index bb877e0..2119ada 100644 --- a/data/CLs/plots/psi2s_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.85Ctt38sTruef.png b/data/CLs/plots/psi2s_p/0.85Ctt38sTruef.png index e0b454f..c464e49 100644 --- a/data/CLs/plots/psi2s_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/psi2s_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/psi2s_p/0.85Ctt39sFalsef.png b/data/CLs/plots/psi2s_p/0.85Ctt39sFalsef.png index ae27d89..fc026f6 100644 --- a/data/CLs/plots/psi2s_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/psi2s_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.00Ctt0sTruef.png b/data/CLs/plots/rho_p/0.00Ctt0sTruef.png index 96722b0..0c642f8 100644 --- a/data/CLs/plots/rho_p/0.00Ctt0sTruef.png +++ b/data/CLs/plots/rho_p/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.00Ctt1sFalsef.png b/data/CLs/plots/rho_p/0.00Ctt1sFalsef.png index e87948c..d2bb12f 100644 --- a/data/CLs/plots/rho_p/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/rho_p/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.25Ctt2sTruef.png b/data/CLs/plots/rho_p/0.25Ctt2sTruef.png index 3694230..ab6f90f 100644 --- a/data/CLs/plots/rho_p/0.25Ctt2sTruef.png +++ b/data/CLs/plots/rho_p/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.25Ctt3sFalsef.png b/data/CLs/plots/rho_p/0.25Ctt3sFalsef.png index 735135a..95cde77 100644 --- a/data/CLs/plots/rho_p/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/rho_p/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.31Ctt4sTruef.png b/data/CLs/plots/rho_p/0.31Ctt4sTruef.png index ad3e890..d363e84 100644 --- a/data/CLs/plots/rho_p/0.31Ctt4sTruef.png +++ b/data/CLs/plots/rho_p/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.31Ctt5sFalsef.png b/data/CLs/plots/rho_p/0.31Ctt5sFalsef.png index 811637e..3ae6fa2 100644 --- a/data/CLs/plots/rho_p/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/rho_p/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.36Ctt6sTruef.png b/data/CLs/plots/rho_p/0.36Ctt6sTruef.png index 02b859a..7917361 100644 --- a/data/CLs/plots/rho_p/0.36Ctt6sTruef.png +++ b/data/CLs/plots/rho_p/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.36Ctt7sFalsef.png b/data/CLs/plots/rho_p/0.36Ctt7sFalsef.png index 55abf70..6df6b46 100644 --- a/data/CLs/plots/rho_p/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/rho_p/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.41Ctt8sTruef.png b/data/CLs/plots/rho_p/0.41Ctt8sTruef.png index 17c9ca0..40e6411 100644 --- a/data/CLs/plots/rho_p/0.41Ctt8sTruef.png +++ b/data/CLs/plots/rho_p/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.41Ctt9sFalsef.png b/data/CLs/plots/rho_p/0.41Ctt9sFalsef.png index 14a3579..a402a56 100644 --- a/data/CLs/plots/rho_p/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/rho_p/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.45Ctt10sTruef.png b/data/CLs/plots/rho_p/0.45Ctt10sTruef.png index b2cd4eb..a743d77 100644 --- a/data/CLs/plots/rho_p/0.45Ctt10sTruef.png +++ b/data/CLs/plots/rho_p/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.45Ctt11sFalsef.png b/data/CLs/plots/rho_p/0.45Ctt11sFalsef.png index 98b259b..af53a90 100644 --- a/data/CLs/plots/rho_p/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/rho_p/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.49Ctt12sTruef.png b/data/CLs/plots/rho_p/0.49Ctt12sTruef.png index 5689a66..c838930 100644 --- a/data/CLs/plots/rho_p/0.49Ctt12sTruef.png +++ b/data/CLs/plots/rho_p/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.49Ctt13sFalsef.png b/data/CLs/plots/rho_p/0.49Ctt13sFalsef.png index f0b7d8a..f88858e 100644 --- a/data/CLs/plots/rho_p/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/rho_p/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.53Ctt14sTruef.png b/data/CLs/plots/rho_p/0.53Ctt14sTruef.png index dcd433f..68ad4de 100644 --- a/data/CLs/plots/rho_p/0.53Ctt14sTruef.png +++ b/data/CLs/plots/rho_p/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.53Ctt15sFalsef.png b/data/CLs/plots/rho_p/0.53Ctt15sFalsef.png index 4a75845..8601507 100644 --- a/data/CLs/plots/rho_p/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/rho_p/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.56Ctt16sTruef.png b/data/CLs/plots/rho_p/0.56Ctt16sTruef.png index 4338aaf..8db5d71 100644 --- a/data/CLs/plots/rho_p/0.56Ctt16sTruef.png +++ b/data/CLs/plots/rho_p/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.56Ctt17sFalsef.png b/data/CLs/plots/rho_p/0.56Ctt17sFalsef.png index ae393e3..b09cae8 100644 --- a/data/CLs/plots/rho_p/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/rho_p/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.59Ctt18sTruef.png b/data/CLs/plots/rho_p/0.59Ctt18sTruef.png index 7ce012b..049190b 100644 --- a/data/CLs/plots/rho_p/0.59Ctt18sTruef.png +++ b/data/CLs/plots/rho_p/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.59Ctt19sFalsef.png b/data/CLs/plots/rho_p/0.59Ctt19sFalsef.png index 4d9cdca..bd07ca7 100644 --- a/data/CLs/plots/rho_p/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/rho_p/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.62Ctt20sTruef.png b/data/CLs/plots/rho_p/0.62Ctt20sTruef.png index 7e62215..388f75f 100644 --- a/data/CLs/plots/rho_p/0.62Ctt20sTruef.png +++ b/data/CLs/plots/rho_p/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.62Ctt21sFalsef.png b/data/CLs/plots/rho_p/0.62Ctt21sFalsef.png index 47e1842..0d505b0 100644 --- a/data/CLs/plots/rho_p/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/rho_p/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.65Ctt22sTruef.png b/data/CLs/plots/rho_p/0.65Ctt22sTruef.png index 6c99e66..7add373 100644 --- a/data/CLs/plots/rho_p/0.65Ctt22sTruef.png +++ b/data/CLs/plots/rho_p/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.65Ctt23sFalsef.png b/data/CLs/plots/rho_p/0.65Ctt23sFalsef.png index a2ea669..526bba2 100644 --- a/data/CLs/plots/rho_p/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/rho_p/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.68Ctt24sTruef.png b/data/CLs/plots/rho_p/0.68Ctt24sTruef.png index 01f56a3..c4fd974 100644 --- a/data/CLs/plots/rho_p/0.68Ctt24sTruef.png +++ b/data/CLs/plots/rho_p/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.68Ctt25sFalsef.png b/data/CLs/plots/rho_p/0.68Ctt25sFalsef.png index 7fea781..79e1f4e 100644 --- a/data/CLs/plots/rho_p/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/rho_p/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.70Ctt26sTruef.png b/data/CLs/plots/rho_p/0.70Ctt26sTruef.png index b11d787..e04a352 100644 --- a/data/CLs/plots/rho_p/0.70Ctt26sTruef.png +++ b/data/CLs/plots/rho_p/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.70Ctt27sFalsef.png b/data/CLs/plots/rho_p/0.70Ctt27sFalsef.png index e153b22..8d95087 100644 --- a/data/CLs/plots/rho_p/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/rho_p/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.73Ctt28sTruef.png b/data/CLs/plots/rho_p/0.73Ctt28sTruef.png index d26d009..8f29db9 100644 --- a/data/CLs/plots/rho_p/0.73Ctt28sTruef.png +++ b/data/CLs/plots/rho_p/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.73Ctt29sFalsef.png b/data/CLs/plots/rho_p/0.73Ctt29sFalsef.png index 8991cd7..326d632 100644 --- a/data/CLs/plots/rho_p/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/rho_p/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.75Ctt30sTruef.png b/data/CLs/plots/rho_p/0.75Ctt30sTruef.png index 43e92d4..1bf4ecc 100644 --- a/data/CLs/plots/rho_p/0.75Ctt30sTruef.png +++ b/data/CLs/plots/rho_p/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.75Ctt31sFalsef.png b/data/CLs/plots/rho_p/0.75Ctt31sFalsef.png index de88c98..f93d109 100644 --- a/data/CLs/plots/rho_p/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/rho_p/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.78Ctt32sTruef.png b/data/CLs/plots/rho_p/0.78Ctt32sTruef.png index 5703fdc..6fa848e 100644 --- a/data/CLs/plots/rho_p/0.78Ctt32sTruef.png +++ b/data/CLs/plots/rho_p/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.78Ctt33sFalsef.png b/data/CLs/plots/rho_p/0.78Ctt33sFalsef.png index c1271a3..22216de 100644 --- a/data/CLs/plots/rho_p/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/rho_p/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.80Ctt34sTruef.png b/data/CLs/plots/rho_p/0.80Ctt34sTruef.png index e66e617..98aca65 100644 --- a/data/CLs/plots/rho_p/0.80Ctt34sTruef.png +++ b/data/CLs/plots/rho_p/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.80Ctt35sFalsef.png b/data/CLs/plots/rho_p/0.80Ctt35sFalsef.png index 35ea7f2..36e1e4d 100644 --- a/data/CLs/plots/rho_p/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/rho_p/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.82Ctt36sTruef.png b/data/CLs/plots/rho_p/0.82Ctt36sTruef.png index 912fb2f..cd65fd4 100644 --- a/data/CLs/plots/rho_p/0.82Ctt36sTruef.png +++ b/data/CLs/plots/rho_p/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.82Ctt37sFalsef.png b/data/CLs/plots/rho_p/0.82Ctt37sFalsef.png index f8f0edb..a19a24d 100644 --- a/data/CLs/plots/rho_p/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/rho_p/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.85Ctt38sTruef.png b/data/CLs/plots/rho_p/0.85Ctt38sTruef.png index ce5a03c..e3e9190 100644 --- a/data/CLs/plots/rho_p/0.85Ctt38sTruef.png +++ b/data/CLs/plots/rho_p/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_p/0.85Ctt39sFalsef.png b/data/CLs/plots/rho_p/0.85Ctt39sFalsef.png index 7b8ceb5..3635be7 100644 --- a/data/CLs/plots/rho_p/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/rho_p/0.85Ctt39sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.00Ctt0sTruef.png b/data/CLs/plots/rho_s/0.00Ctt0sTruef.png index 36482de..02dfae8 100644 --- a/data/CLs/plots/rho_s/0.00Ctt0sTruef.png +++ b/data/CLs/plots/rho_s/0.00Ctt0sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.00Ctt1sFalsef.png b/data/CLs/plots/rho_s/0.00Ctt1sFalsef.png index f9e0c14..8f4bf3f 100644 --- a/data/CLs/plots/rho_s/0.00Ctt1sFalsef.png +++ b/data/CLs/plots/rho_s/0.00Ctt1sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.25Ctt2sTruef.png b/data/CLs/plots/rho_s/0.25Ctt2sTruef.png index 5462262..39df07d 100644 --- a/data/CLs/plots/rho_s/0.25Ctt2sTruef.png +++ b/data/CLs/plots/rho_s/0.25Ctt2sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.25Ctt3sFalsef.png b/data/CLs/plots/rho_s/0.25Ctt3sFalsef.png index 2d32aee..b25e1c2 100644 --- a/data/CLs/plots/rho_s/0.25Ctt3sFalsef.png +++ b/data/CLs/plots/rho_s/0.25Ctt3sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.31Ctt4sTruef.png b/data/CLs/plots/rho_s/0.31Ctt4sTruef.png index 705691f..a4fdd2e 100644 --- a/data/CLs/plots/rho_s/0.31Ctt4sTruef.png +++ b/data/CLs/plots/rho_s/0.31Ctt4sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.31Ctt5sFalsef.png b/data/CLs/plots/rho_s/0.31Ctt5sFalsef.png index 41b19bc..5577374 100644 --- a/data/CLs/plots/rho_s/0.31Ctt5sFalsef.png +++ b/data/CLs/plots/rho_s/0.31Ctt5sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.36Ctt6sTruef.png b/data/CLs/plots/rho_s/0.36Ctt6sTruef.png index 296be0c..07681e4 100644 --- a/data/CLs/plots/rho_s/0.36Ctt6sTruef.png +++ b/data/CLs/plots/rho_s/0.36Ctt6sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.36Ctt7sFalsef.png b/data/CLs/plots/rho_s/0.36Ctt7sFalsef.png index 01b3317..41131df 100644 --- a/data/CLs/plots/rho_s/0.36Ctt7sFalsef.png +++ b/data/CLs/plots/rho_s/0.36Ctt7sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.41Ctt8sTruef.png b/data/CLs/plots/rho_s/0.41Ctt8sTruef.png index 50741e9..8ff5dde 100644 --- a/data/CLs/plots/rho_s/0.41Ctt8sTruef.png +++ b/data/CLs/plots/rho_s/0.41Ctt8sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.41Ctt9sFalsef.png b/data/CLs/plots/rho_s/0.41Ctt9sFalsef.png index f5c6d12..ea64ec2 100644 --- a/data/CLs/plots/rho_s/0.41Ctt9sFalsef.png +++ b/data/CLs/plots/rho_s/0.41Ctt9sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.45Ctt10sTruef.png b/data/CLs/plots/rho_s/0.45Ctt10sTruef.png index a08bd8c..6e0823c 100644 --- a/data/CLs/plots/rho_s/0.45Ctt10sTruef.png +++ b/data/CLs/plots/rho_s/0.45Ctt10sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.45Ctt11sFalsef.png b/data/CLs/plots/rho_s/0.45Ctt11sFalsef.png index ef55e65..912cd08 100644 --- a/data/CLs/plots/rho_s/0.45Ctt11sFalsef.png +++ b/data/CLs/plots/rho_s/0.45Ctt11sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.49Ctt12sTruef.png b/data/CLs/plots/rho_s/0.49Ctt12sTruef.png index fe76536..474e658 100644 --- a/data/CLs/plots/rho_s/0.49Ctt12sTruef.png +++ b/data/CLs/plots/rho_s/0.49Ctt12sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.49Ctt13sFalsef.png b/data/CLs/plots/rho_s/0.49Ctt13sFalsef.png index 26555a1..3d7fbfc 100644 --- a/data/CLs/plots/rho_s/0.49Ctt13sFalsef.png +++ b/data/CLs/plots/rho_s/0.49Ctt13sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.53Ctt14sTruef.png b/data/CLs/plots/rho_s/0.53Ctt14sTruef.png index 849a19a..802c474 100644 --- a/data/CLs/plots/rho_s/0.53Ctt14sTruef.png +++ b/data/CLs/plots/rho_s/0.53Ctt14sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.53Ctt15sFalsef.png b/data/CLs/plots/rho_s/0.53Ctt15sFalsef.png index 6b8ded4..1c50761 100644 --- a/data/CLs/plots/rho_s/0.53Ctt15sFalsef.png +++ b/data/CLs/plots/rho_s/0.53Ctt15sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.56Ctt16sTruef.png b/data/CLs/plots/rho_s/0.56Ctt16sTruef.png index 1e9480a..1dc98c3 100644 --- a/data/CLs/plots/rho_s/0.56Ctt16sTruef.png +++ b/data/CLs/plots/rho_s/0.56Ctt16sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.56Ctt17sFalsef.png b/data/CLs/plots/rho_s/0.56Ctt17sFalsef.png index 706f08e..3939845 100644 --- a/data/CLs/plots/rho_s/0.56Ctt17sFalsef.png +++ b/data/CLs/plots/rho_s/0.56Ctt17sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.59Ctt18sTruef.png b/data/CLs/plots/rho_s/0.59Ctt18sTruef.png index aafb96d..fe148b7 100644 --- a/data/CLs/plots/rho_s/0.59Ctt18sTruef.png +++ b/data/CLs/plots/rho_s/0.59Ctt18sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.59Ctt19sFalsef.png b/data/CLs/plots/rho_s/0.59Ctt19sFalsef.png index 5988bac..1210a05 100644 --- a/data/CLs/plots/rho_s/0.59Ctt19sFalsef.png +++ b/data/CLs/plots/rho_s/0.59Ctt19sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.62Ctt20sTruef.png b/data/CLs/plots/rho_s/0.62Ctt20sTruef.png index 063df13..f2dbb97 100644 --- a/data/CLs/plots/rho_s/0.62Ctt20sTruef.png +++ b/data/CLs/plots/rho_s/0.62Ctt20sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.62Ctt21sFalsef.png b/data/CLs/plots/rho_s/0.62Ctt21sFalsef.png index a7226f9..0aee7ef 100644 --- a/data/CLs/plots/rho_s/0.62Ctt21sFalsef.png +++ b/data/CLs/plots/rho_s/0.62Ctt21sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.65Ctt22sTruef.png b/data/CLs/plots/rho_s/0.65Ctt22sTruef.png index 5972dd8..7a0532d 100644 --- a/data/CLs/plots/rho_s/0.65Ctt22sTruef.png +++ b/data/CLs/plots/rho_s/0.65Ctt22sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.65Ctt23sFalsef.png b/data/CLs/plots/rho_s/0.65Ctt23sFalsef.png index ac50065..2857671 100644 --- a/data/CLs/plots/rho_s/0.65Ctt23sFalsef.png +++ b/data/CLs/plots/rho_s/0.65Ctt23sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.68Ctt24sTruef.png b/data/CLs/plots/rho_s/0.68Ctt24sTruef.png index 12f27b2..573e90b 100644 --- a/data/CLs/plots/rho_s/0.68Ctt24sTruef.png +++ b/data/CLs/plots/rho_s/0.68Ctt24sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.68Ctt25sFalsef.png b/data/CLs/plots/rho_s/0.68Ctt25sFalsef.png index e00efd1..3db9afe 100644 --- a/data/CLs/plots/rho_s/0.68Ctt25sFalsef.png +++ b/data/CLs/plots/rho_s/0.68Ctt25sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.70Ctt26sTruef.png b/data/CLs/plots/rho_s/0.70Ctt26sTruef.png index b26815c..7788e94 100644 --- a/data/CLs/plots/rho_s/0.70Ctt26sTruef.png +++ b/data/CLs/plots/rho_s/0.70Ctt26sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.70Ctt27sFalsef.png b/data/CLs/plots/rho_s/0.70Ctt27sFalsef.png index 451df4d..25a2af0 100644 --- a/data/CLs/plots/rho_s/0.70Ctt27sFalsef.png +++ b/data/CLs/plots/rho_s/0.70Ctt27sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.73Ctt28sTruef.png b/data/CLs/plots/rho_s/0.73Ctt28sTruef.png index 078637d..c2b986d 100644 --- a/data/CLs/plots/rho_s/0.73Ctt28sTruef.png +++ b/data/CLs/plots/rho_s/0.73Ctt28sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.73Ctt29sFalsef.png b/data/CLs/plots/rho_s/0.73Ctt29sFalsef.png index 84f6a82..f53cf58 100644 --- a/data/CLs/plots/rho_s/0.73Ctt29sFalsef.png +++ b/data/CLs/plots/rho_s/0.73Ctt29sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.75Ctt30sTruef.png b/data/CLs/plots/rho_s/0.75Ctt30sTruef.png index 574420e..7618f72 100644 --- a/data/CLs/plots/rho_s/0.75Ctt30sTruef.png +++ b/data/CLs/plots/rho_s/0.75Ctt30sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.75Ctt31sFalsef.png b/data/CLs/plots/rho_s/0.75Ctt31sFalsef.png index 3a5ab4a..3478b89 100644 --- a/data/CLs/plots/rho_s/0.75Ctt31sFalsef.png +++ b/data/CLs/plots/rho_s/0.75Ctt31sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.78Ctt32sTruef.png b/data/CLs/plots/rho_s/0.78Ctt32sTruef.png index 46a2551..71f157f 100644 --- a/data/CLs/plots/rho_s/0.78Ctt32sTruef.png +++ b/data/CLs/plots/rho_s/0.78Ctt32sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.78Ctt33sFalsef.png b/data/CLs/plots/rho_s/0.78Ctt33sFalsef.png index 09aa5d7..3cf0e5d 100644 --- a/data/CLs/plots/rho_s/0.78Ctt33sFalsef.png +++ b/data/CLs/plots/rho_s/0.78Ctt33sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.80Ctt34sTruef.png b/data/CLs/plots/rho_s/0.80Ctt34sTruef.png index 2eb83cc..9c9b528 100644 --- a/data/CLs/plots/rho_s/0.80Ctt34sTruef.png +++ b/data/CLs/plots/rho_s/0.80Ctt34sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.80Ctt35sFalsef.png b/data/CLs/plots/rho_s/0.80Ctt35sFalsef.png index b7be2ea..b629428 100644 --- a/data/CLs/plots/rho_s/0.80Ctt35sFalsef.png +++ b/data/CLs/plots/rho_s/0.80Ctt35sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.82Ctt36sTruef.png b/data/CLs/plots/rho_s/0.82Ctt36sTruef.png index 29768f5..ad1f882 100644 --- a/data/CLs/plots/rho_s/0.82Ctt36sTruef.png +++ b/data/CLs/plots/rho_s/0.82Ctt36sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.82Ctt37sFalsef.png b/data/CLs/plots/rho_s/0.82Ctt37sFalsef.png index 55c2239..a6fcff7 100644 --- a/data/CLs/plots/rho_s/0.82Ctt37sFalsef.png +++ b/data/CLs/plots/rho_s/0.82Ctt37sFalsef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.85Ctt38sTruef.png b/data/CLs/plots/rho_s/0.85Ctt38sTruef.png index 3014feb..fcc1172 100644 --- a/data/CLs/plots/rho_s/0.85Ctt38sTruef.png +++ b/data/CLs/plots/rho_s/0.85Ctt38sTruef.png Binary files differ diff --git a/data/CLs/plots/rho_s/0.85Ctt39sFalsef.png b/data/CLs/plots/rho_s/0.85Ctt39sFalsef.png index 38c6189..3c4f902 100644 --- a/data/CLs/plots/rho_s/0.85Ctt39sFalsef.png +++ b/data/CLs/plots/rho_s/0.85Ctt39sFalsef.png Binary files differ diff --git a/raremodel-nb.ipynb b/raremodel-nb.ipynb index 8e79b17..269c82d 100644 --- a/raremodel-nb.ipynb +++ b/raremodel-nb.ipynb @@ -2188,7 +2188,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "Number of jobs: 374\n" + "Number of jobs: 774\n" ] } ], @@ -2351,12 +2351,12 @@ "name": "stdout", "output_type": "stream", "text": [ - "(20, 374)\n" + "(20, 774)\n" ] }, { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAEWCAYAAAB/tMx4AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAZj0lEQVR4nO3de5RdZX3G8e9jDNeQJiEDhoQwKFihFKIdI5bWUkBXuKiwShGkFig0WMsSW5SitgW71EKrYi1WGwXJqoBcFURoiQrejU4wYGKiQIwSEpOBECCCSsKvf7zv4MnknJkz55p35vmsNWvO2WefvX/7XJ7z7nffFBGYmVl5XtDtAszMrDEOcDOzQjnAzcwK5QA3MyuUA9zMrFAOcDOzQjnA6ySpV1JIemG+f4+kc7pdl42epCMlrel2HZ0m6f2SHpX0i6Gf5xbP548l/bjV021GXvaru11Hq427AJe0WtIzkjZLWi/pM5ImtXgel0h6VtJT+e8nkq6QNKNinCMlPZfr2CxpjaQbJL2yznlcLen9ray7nSTNlXSHpE2SNkr6nqSz8mPbBWp+DT/bnWobl4PxbklPS1op6Zhhxp0m6focqo9KukbS5IrHKz+rmyXd1URd+wIXAAdHxIsanU6NaYekAwbvR8Q3IuJ3WzmPinndI+lXFa/JZkmvbse8SjDuAjx7fURMAl4BvBL4xzbM4/qI2AOYBpwEvAhYUhniwNpcxx7A4cBK4BuSjm5DPdtoR8trmHm9Gvgq8DXgAGBP4G+AYztVQwddB/yAtIzvBW6S1FNj3PcDU4EXAy8B9gYuGTLO6yNiUv57XRN17Qc8FhEbmpjGjuK8itdkUkR8p9sFdct4DXAAIuIR4E7gEHi+xfN8i6kVrcCIeDYilgNvAgZIraCh40RErImIfwY+DVyW5y9Jl0vaIOkJSfdLOkTSfOB04MLcAvliHv8iSQ/lVv+PJJ1UsSxnSvpWnt5Gtg8Kqoz7n3m+K5v8Ufl3YGFEXBYRj+blXRIRp0janfQe7FPRonoz8B7gTfn+fVVqvEjSTUOG/Yekj+XbZ0lakV+LVZLOHWZ5t2lBDl27kXSCpKV57eHbkg6tMZ2XkhoFF0fEMxFxM/BD4M9qzHp/4AsR8WREPAF8Hvi9WnU2Kn+mF/Hb1/jqKuPsI+m2vHb0oKS/rnhsrqTv5OVfl9cmd8qPfT2Pdl+e9puGrlHl79U78+f3ibzWsUvF4xfm6a6VdM7Q92MUy3mF0prsk5K+L+kPa4y3m6RrJT2Wl+l7kqbnx6YorZWvy9P6F0k7bE7usIV1Ql6tPI7UYmqriNgK3Ar88Qij3gK8Igfb64DXAC8FppB+BB6LiAXANcC/5RbI6/NzH8rT/x3gfcBnh7T4XwWsAvYCPjBCHYPjTgcuBm6RNK2eZa0kaTfg1cBN1R6PiF+SWuJrK1pU1wIfJK3FTIqIw6o89TrgOOUuB0kTgFOAa/PjG4ATgMnAWcDlkl7RQP2vAK4CziW1qv8buE3SzlVG/z1gVUQ8VTHsPmqH8seBEyRNlTSVFPR3DhnnGkkDku6SVO11GFFEfJltX+Mzq4x2HbAG2Ac4GfhgxY/2VuDvSJ+FVwNHA2/L035NHuewPO3ra5RxCjCP9KN1KHAmgKR5wN8Dx5DWzv6kkWXMFudpTyN93m6s8T6dBewGzCK9p28DfpUf+yzwDGmNqA84Po+/QxqvAf4FSZuAb5JW6z/YofmuJX24RhpHpMB+ltS98jJAEbEiItbVemJE3BgRayPiufxFegCYWzntiPjPiNgSEc+MUMcG4KN5DeJ64MekD/NoTSV9zmrW3YiI+BlwL3BiHnQU8HREfDc//qWIeCi39r8G3MXIP57V/DXw3xGxOCK2RsRC4NekLq+hJgFPDBn2BOk9rOZeYCfgsfy3FfivisdPB3pJ3R93A/8naUoDyzCs3JD5I+AfIuJXEbGUtCb4FoC8tvTd/LlZTfoRG23Qfix/NjcCXwTm5OGnAJ+JiOUR8TSp4THitHLLeZOkewcHRsT/RMTGiNgC/Bvpx7taS/5Z0o/RAfk97Y+IzZJmkn6c/i4ino6IXwAfBU4d5bJ2zHgN8BMjYkpE7BcRb6sjzFplJrCxjnEC2BQRXwWuILXU1ktaoIqNXENJ+suKVf1NpK6h6RWjPDyKWh+Jbc909jNS62zoPE+v6PoY2noEeBx4DphR5bFmXQuclm+/md+2vpF0rKTv5i6BTaQ1relVpjGS/YALKgJjE7AvVV4LYDMpNCpNBp6qMi7AjcBPSAE/mbQG9XyXXUR8K3fFPB0R/wpsosqPkKTZFe/B5lEuH6Rl2ThkzeFnpM8ikl4q6XalvVeeJDV4Rvta/qLi9tOkH7vBeVd+Luv5jL49f3+nRMTza1W5K2alpCdIn7vda9R5NfBl4AZJj0i6VGmb0H7AzqTv2uB7/XHStokd0ngN8Fp+SVq1GtSyrfW5H+31wDdGGPUk4N7ctUBEfCwi/oC0Gv5S4F15vG1OIylpP+BTwHnAnhExBVhGas1T7TkjmCmp8rmzSWsH24iIayq6PrbbKJlbVd+hdj9wrbrqqfVG4EhJs0iv27UAebX5ZuBDwN75tbiDbV+LSk9T+31/GPhARWBMiYjdIuK6KtNZDrxYUmWL+7A8vJrDSK37X0bEZuCTpB+aWqLaMkTEzys36g3z/FrWAtOG1D0beCTf/gRpA/uBETGZtH2i1ms5WutIXRmD9m1kIpL+lNQV82ektdeppB/Uaq/XbyLikog4iLTmcRJpbedh0mdhWsV7PTkiqm7z2BE4wLe1FDhV0kRJfaS+wKbkaR1E6mN8EfCRKuNI0kxJFwPnkL4gSHqlpFdJmkj6cfkVaTUbYD1p74VBu5O+4AP5uWeRN842aC/g7bn+PwcOIoVgIy4EzpT0Lkl75voOk/S5/Ph6YE9Jv1PxnPVA73AbkCJiALgH+Azw04hYkR/aidSSGgC2SDqWtD2hlqXAmyVNyH2yld0DnwLemt8HSdpd0vFDwm6wnp/kaV0saReljciHkn5Mqvk+cI6kXSXtCswn9ZkPtqqPkLRTnta7SK3Jbw2zHA2JiIeBbwP/mud1KHA2aTsLpDWEJ4HNkl5G2oOo0tDP4mjcAJwl6aC8veSfG5zOHsAW4FFgImkj/e7VRpR0lNLOAC8gLdezwNb8OnwN+JCkyZJeIOkASa+pNp0dgQN8W/9E2njxOKkv7trhRx/Wm/Lq7CbgNlIf5x9ERGUrdp88zmbSl/n3gSMjYnB/38mkAHmctEr7GKlVCXAlcHBe1ftCRPwI+DCptbs+T6uZL/ti4EDSF+IDwMkR8VgjE4qIb5P6qI8CVintBbOA/IMQEStJP3Cr8vLsQ2pdAzxW2c9ZxbWkDWDPv1e5K+DtpHB4nNS9ctsw0ziftHa0idQS+0LFtPpJ/eBX5Gk9SN4AV8OppI1fjwOXkl63wR/V0yVVtsb/itTHvYbU2n1xxbT3ILV8H8+PzQOObfQ9qMNpuZa1pL1hLo6IRfmxd5Jew6dIn8ehGyovARbm9+6U0cw0Iu4EPkbq43+Q9PmFtJ1hNO4gdYs8AKwmBXOt7S77kHYWeJK0dvRl0ucP4C9Iwf8j0mt/Iy1cE281hS/oYENIOhM4JyL+qNu12PiS11aXATvnjZE2DLfAzayrJJ2Uu4qmko6B+KLDuz4O8HFK0ie17eHIg3+f7HZtNu6cS9pe8RBpG8/QPnarwV0oZmaFcgvczKxQHTuhEcD06dOjt7e3k7M0MyvekiVLHo2I7U6K1tEA7+3tpb+/v5OzNDMrnqSfVRvuLhQzs0I5wM3MCuUANzMrlAPczKxQDnAzs0I5wM3MCuUANzMrlAPczKxQDnAzs0J19EhMG7t6L/pS1eGrL23kOshmVg+3wM3MClV3gOfrBf5A0u35/v6SFkt6QNL1knZqX5lmZjbUaFrg5wMrKu5fBlweEQeSrh13disLMzOz4dUV4JJmAccDn873RbpA7U15lIXAie0o0MzMqqu3Bf5R4ELguXx/T2BTxXXr1gAzqz1R0nxJ/ZL6BwYGmirWzMx+a8QAl3QCsCEillQOrjJq1WuzRcSCiOiLiL6enu3OR25mZg2qZzfCI4A3SDoO2AWYTGqRT5H0wtwKnwWsbV+ZZmY21Igt8Ih4d0TMiohe4FTgqxFxOnA3cHIe7Qzg1rZVaWZm22lmP/B/AP5e0oOkPvErW1OSmZnVY1RHYkbEPcA9+fYqYG7rSzIzs3r4SEwzs0I5wM3MCuUANzMrlAPczKxQDnAzs0I5wM3MCuUANzMrlAPczKxQDnAzs0I5wM3MCuUANzMrlAPczKxQDnAzs0I5wM3MCuUANzMrlAPczKxQ9VzUeBdJ35N0n6Tlkt6Xh18t6aeSlua/Oe0v18zMBtVzRZ5fA0dFxGZJE4FvSrozP/auiLipfeWZmVktIwZ4RASwOd+dmP+inUWZmdnI6uoDlzRB0lJgA7AoIhbnhz4g6X5Jl0vaucZz50vql9Q/MDDQorLNzKyuAI+IrRExB5gFzJV0CPBu4GXAK4FppKvUV3vugojoi4i+np6eFpVtZmaj2gslIjaRrko/LyLWRfJr4DP4CvVmZh1Vz14oPZKm5Nu7AscAKyXNyMMEnAgsa2ehZma2rXr2QpkBLJQ0gRT4N0TE7ZK+KqkHELAUeGsb6zQzsyHq2QvlfuDlVYYf1ZaKzMysLj4S08ysUA5wM7NCOcDNzArlADczK5QD3MysUA5wM7NCOcDNzArlADczK5QD3MysUPUcSm/WMb0Xfanq8NWXHt/hSsx2fG6Bm5kVygFuZlYoB7iZWaEc4GZmhXKAm5kVygFuZlaoei6ptouk70m6T9JySe/Lw/eXtFjSA5Kul7RT+8s1M7NB9bTAfw0cFRGHAXOAeZIOBy4DLo+IA4HHgbPbV6aZmQ01YoDnK89vzncn5r8AjgJuysMXki5sbGZmHVJXH7ikCZKWAhuARcBDwKaI2JJHWQPMrPHc+ZL6JfUPDAy0omYzM6POAI+IrRExB5gFzAUOqjZajecuiIi+iOjr6elpvFIzM9vGqPZCiYhNwD3A4cAUSYPnUpkFrG1taWZmNpx69kLpkTQl394VOAZYAdwNnJxHOwO4tV1FmpnZ9uo5G+EMYKGkCaTAvyEibpf0I+Bzkt4P/AC4so11mpnZECMGeETcD7y8yvBVpP5wMzPrAh+JaWZWKAe4mVmhHOBmZoVygJuZFcrXxLRRqXXNym5Nx2w8cwvczKxQDnAzs0I5wM3MCuUANzMrlDdiWlt5Y6VZ+7gFbmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWKAe4mVmh6rmk2r6S7pa0QtJySefn4ZdIekTS0vx3XPvLNTOzQfXsB74FuCAi7pW0B7BE0qL82OUR8aH2lWdmZrXUc0m1dcC6fPspSSuAme0uzMzMhjeqPnBJvaTrYy7Og86TdL+kqyRNbXFtZmY2jLoDXNIk4GbgHRHxJPAJ4CXAHFIL/cM1njdfUr+k/oGBgRaUbGZmUGeAS5pICu9rIuIWgIhYHxFbI+I54FPUuEJ9RCyIiL6I6Ovp6WlV3WZm4149e6EIuBJYEREfqRg+o2K0k4BlrS/PzMxqqWcvlCOAtwA/lLQ0D3sPcJqkOUAAq4Fz21KhmZlVVc9eKN8EVOWhO1pfjpmZ1ctHYpqZFcoBbmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWKAe4mVmhHOBmZoVygJuZFaqea2LuK+luSSskLZd0fh4+TdIiSQ/k/1PbX66ZmQ2qpwW+BbggIg4CDgf+VtLBwEXAVyLiQOAr+b6ZmXXIiAEeEesi4t58+ylgBTATeCOwMI+2EDixXUWamdn26rkq/fMk9QIvBxYDe0fEOkghL2mvGs+ZD8wHmD17djO1mhWt96IvVR2++tLjO1yJjRV1b8SUNAm4GXhHRDxZ7/MiYkFE9EVEX09PTyM1mplZFXUFuKSJpPC+JiJuyYPXS5qRH58BbGhPiWZmVk09e6EIuBJYEREfqXjoNuCMfPsM4NbWl2dmZrXU0wd+BPAW4IeSluZh7wEuBW6QdDbwc+DP21OimZlVM2KAR8Q3AdV4+OjWlmNmZvXykZhmZoVygJuZFcoBbmZWKAe4mVmhRnUkplm3tOooRh8NaWOJW+BmZoVygJuZFcoBbmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWqHouqXaVpA2SllUMu0TSI5KW5r/j2lummZkNVU8L/GpgXpXhl0fEnPx3R2vLMjOzkYwY4BHxdWBjB2oxM7NRaOZ0sudJ+kugH7ggIh6vNpKk+cB8gNmzZzcxO2s1n1q1OX79rNsa3Yj5CeAlwBxgHfDhWiNGxIKI6IuIvp6engZnZ2ZmQzUU4BGxPiK2RsRzwKeAua0ty8zMRtJQgEuaUXH3JGBZrXHNzKw9RuwDl3QdcCQwXdIa4GLgSElzgABWA+e2sUYzM6tixACPiNOqDL6yDbWYmdko+EhMM7NCOcDNzArlADczK5QD3MysUA5wM7NCOcDNzArlADczK5QD3MysUA5wM7NCNXM6WRujap0m1TrLp6u1kbgFbmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWKAe4mVmhRgxwSVdJ2iBpWcWwaZIWSXog/5/a3jLNzGyoelrgVwPzhgy7CPhKRBwIfCXfNzOzDhoxwCPi68DGIYPfCCzMtxcCJ7a4LjMzG0GjR2LuHRHrACJinaS9ao0oaT4wH2D27NkNzs6svVp51KOPZLVOaftGzIhYEBF9EdHX09PT7tmZmY0bjQb4ekkzAPL/Da0ryczM6tFogN8GnJFvnwHc2ppyzMysXvXsRngd8B3gdyWtkXQ2cCnwWkkPAK/N983MrING3IgZEafVeOjoFtdiNmrt3mDoDZK2I/ORmGZmhXKAm5kVygFuZlYoB7iZWaEc4GZmhXKAm5kVygFuZlYoB7iZWaEc4GZmhXKAm5kVygFuZlYoB7iZWaEc4GZmhXKAm5kVqtFrYppZi3TrlLiNXO/TdixugZuZFaqpFrik1cBTwFZgS0T0taIoMzMbWSu6UP40Ih5twXTMzGwU3IViZlaoZgM8gLskLZE0vxUFmZlZfZrtQjkiItZK2gtYJGllRHy9coQc7PMBZs+e3eTszMxsUFMt8IhYm/9vAD4PzK0yzoKI6IuIvp6enmZmZ2ZmFRoOcEm7S9pj8DbwOmBZqwozM7PhNdOFsjfweUmD07k2Iv63JVWZmdmIGg7wiFgFHNbCWszMbBR8KH0HdeuQ5nYfqm2d1e7PkQ+9L4f3AzczK5QD3MysUA5wM7NCOcDNzArljZgF8kZJa4XRfo68cXPH4xa4mVmhHOBmZoVygJuZFcoBbmZWKEVEx2bW19cX/f39HZtfNcNtuKm1MaZVG2+88dHGG2/gbA1JS6pdstItcDOzQjnAzcwK5QA3MyuUA9zMrFBj9kjMRjYY+sg0s/Gp1O+yW+BmZoVqKsAlzZP0Y0kPSrqoVUWZmdnImrmo8QTg48CxwMHAaZIOblVhZmY2vGZa4HOBByNiVUT8Bvgc8MbWlGVmZiNpZiPmTODhivtrgFcNHUnSfGB+vrtZ0o+bmGe3TAcerXdkXdbGSjpjVMs7RniZ22AH/C6U+l3er9rAZgJcVYZtd1x+RCwAFjQxn66T1F/tMNaxarwtL3iZx4uxtszNdKGsAfatuD8LWNtcOWZmVq9mAvz7wIGS9pe0E3AqcFtryjIzs5E03IUSEVsknQf8HzABuCoilressh1L0V1ADRhvywte5vFiTC1zR08na2ZmreMjMc3MCuUANzMrlAN8FCS9U1JImt7tWtpN0r9LWinpfkmflzSl2zW1y3g7JYSkfSXdLWmFpOWSzu92TZ0gaYKkH0i6vdu1tIoDvE6S9gVeC/y827V0yCLgkIg4FPgJ8O4u19MW4/SUEFuACyLiIOBw4G/HwTIDnA+s6HYRreQAr9/lwIVUOVhpLIqIuyJiS777XdJ+/mPRuDslRESsi4h78+2nSKE2s7tVtZekWcDxwKe7XUsrOcDrIOkNwCMRcV+3a+mSvwLu7HYRbVLtlBBjOswqSeoFXg4s7m4lbfdRUgPsuW4X0kpj9oIOoyXpy8CLqjz0XuA9wOs6W1H7DbfMEXFrHue9pFXuazpZWwfVdUqIsUjSJOBm4B0R8WS362kXSScAGyJiiaQju11PKznAs4g4ptpwSb8P7A/cJwlSV8K9kuZGxC86WGLL1VrmQZLOAE4Ajo6xe8DAuDwlhKSJpPC+JiJu6XY9bXYE8AZJxwG7AJMlfTYi/qLLdTXNB/KMkqTVQF9EjOkz10maB3wE+JOIGOh2Pe0i6YWkjbRHA4+QThHx5jF8VDFKLZGFwMaIeEe36+mk3AJ/Z0Sc0O1aWsF94FbLFcAewCJJSyV9stsFtUPeUDt4SogVwA1jObyzI4C3AEfl93Zpbp1aYdwCNzMrlFvgZmaFcoCbmRXKAW5mVigHuJlZoRzgZmaFcoDbuCBpa95dbpmkGyXtNsL4V0s6Od++R9KYuRCujR0OcBsvnomIORFxCPAb4K3dLsisWQ5wG4++ARwgqVfSssGB+Xzvl3SvLLPRcYDbuJIPnT8W+GG3azFrlgPcxotdJS0F+kkX5biyy/WYNc1nI7Tx4pmImFM5QNIWtm3E7NLZksya4xa4jWfrgb0k7SlpZ9Kpc82K4Ra4jVsR8aykfyFdjeanwMoul2Q2Kj4boZlZodyFYmZWKAe4mVmhHOBmZoVygJuZFcoBbmZWKAe4mVmhHOBmZoX6f0XloYVKt+8JAAAAAElFTkSuQmCC\n", + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAEWCAYAAAB/tMx4AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAZV0lEQVR4nO3de5hddX3v8fdHBJFLGgIDco8eUbEUUEfUQ2spUR8QFHyKiFpPQGjs8XjUVsVUzym0j9rY9ghaPdoUlDxHQC5eiLcWRLDWCxowKBAQSCOEhGSABIhgJfA5f6zfwM5kT2bPzN6z88t8Xs8zz+x12Wt917589m/91tpryzYREVGfp/W7gIiImJgEeEREpRLgERGVSoBHRFQqAR4RUakEeEREpRLgHZA0W5IlPb0MXyvpjH7XFeMn6ShJK/tdx1ST9BFJ90m6d+Trucvr+QNJt3V7uZNRtv2CftfRC9MqwCWtkPSopA2S1kj6gqRduryOsyU9Junh8vdLSZ+WtHfLPEdJeqLUsUHSSkmXSnpph+u4QNJHull3L0k6QtK3JK2X9ICkn0g6rUzbLFDLY/jF/lQ7cSUYr5H0iKRbJb1qC/POknRJCdX7JF0oaUbL9NbX6gZJV06irv2B9wEvtP2siS5nlGVb0nOHh21/3/bzu7mOlnVdK+k3LY/JBkmv6MW6ajGtArx4ne1dgBcDLwX+Vw/WcYntXYFZwBuAZwHXt4Y4sKrUsSvwcuBW4PuS5vSgnk30ouW1hXW9Avgu8D3gucDuwH8Hjp2qGqbQxcDPaLbxw8DlkgZGmfcjwG7Ac4D/AuwFnD1intfZ3qX8vWYSdR0I3G977SSWsbV4V8tjsovtH/W7oH6ajgEOgO17gG8Dh8CTLZ4nW0zdaAXafsz2zcCbgCGaVtDIeWx7pe2/As4DPl7WL0nnSFor6UFJP5d0iKR5wFuBM0sL5Otl/vmS7iyt/lskvaFlW06V9IOyvAfYPChoM+8/lvXeOskPlb8HFtn+uO37yvZeb/tkSTvTPAf7tLSo3gJ8CHhTGb6xTY3zJV0+YtwnJX2q3D5N0rLyWCyX9I4tbO8mLciRezeSjpe0tOw9/FDSoaMs53k0jYKzbD9q+8vAL4A/HmXVzwa+Zvsh2w8CXwV+d7Q6J6q8pq/iqcf4gjbz7CNpcdk7ukPSn7ZMO0LSj8r2ry57kzuUaf9WZruxLPtNI/eoyvvq/eX1+2DZ69ixZfqZZbmrJJ0x8vkYx3Z+Ws2e7EOSfirpv44y306SLpJ0f9mmn0jao0ybqWavfHVZ1t9I2qozcqsurpfKbuVraVpMPWX7ceAK4A/GmPUrwItLsL0GeCXwPGAmzYfA/bYXAhcCf1daIK8r972zLP93gL8Gvjiixf8yYDmwJ/DRMeoYnncP4CzgK5JmdbKtrSTtBLwCuLzddNu/pmmJr2ppUV0EfIxmL2YX24e1uevFwGtVuhwkbQecDFxUpq8FjgdmAKcB50h68QTqfzHweeAdNK3qfwIWS3pGm9l/F1hu++GWcTcyeih/Bjhe0m6SdqMJ+m+PmOdCSUOSrpTU7nEYk+3vsOljfGqb2S4GVgL7ACcBH2v50H4c+HOa18IrgDnAO8uyX1nmOaws+5JRyjgZOIbmQ+tQ4FQASccAfwG8imbv7A8nso3FdWXZs2heb5eN8jydBuwE7EfznL4T+E2Z9kXgUZo9okHguDL/Vms6BvjXJK0H/p1mt/5jU7TeVTQvrrHmEU1gP0bTvfICQLaX2V492h1tX2Z7le0nyhvpduCI1mXb/kfbG20/OkYda4Fzyx7EJcBtNC/m8dqN5jU2at0TYftXwA3AiWXU0cAjtn9cpn/T9p2ltf894ErG/vBs50+Bf7J9ne3HbS8C/pOmy2ukXYAHR4x7kOY5bOcGYAfg/vL3OPB/W6a/FZhN0/1xDfCvkmZOYBu2qDRkfh/4oO3f2F5Ksyf4NoCyt/Tj8rpZQfMhNt6g/VR5bT4AfB04vIw/GfiC7ZttP0LT8BhzWaXlvF7SDcMjbf8/2w/Y3gj8Hc2Hd7uW/GM0H0bPLc/pEtsbJO1L8+H057YfsX0vcC5wyji3dUpNxwA/0fZM2wfafmcHYdYt+wIPdDCPgfW2vwt8mqaltkbSQrUc5BpJ0n9r2dVfT9M1tEfLLHePo9Z7vOlVzn5F0zobuc63tnR9jGw9AqwDngD2bjNtsi4C3lxuv4WnWt9IOlbSj0uXwHqaPa092ixjLAcC72sJjPXA/rR5LIANNKHRagbwcJt5AS4DfkkT8DNo9qCe7LKz/YPSFfOI7b8F1tPmQ0jSAS3PwYZxbh802/LAiD2HX9G8FpH0PEnfUHP2ykM0DZ7xPpb3ttx+hObDbnjdra/LTl6j7y7v35m2n9yrKl0xt0p6kOZ1t/ModV4AfAe4VNI9khaoOSZ0IPAMmvfa8HP9GZpjE1ut6Rjgo/k1za7VsK4drS/9aK8Dvj/GrG8AbihdC9j+lO2X0OyGPw/4QJlvk0tISjoQ+GfgXcDutmcCN9G05ml3nzHsK6n1vgfQ7B1swvaFLV0fmx2ULK2qHzF6P/BodXVS62XAUZL2o3ncLgIou81fBv4B2Ks8Ft9i08ei1SOM/rzfDXy0JTBm2t7J9sVtlnMz8BxJrS3uw8r4dg6jad3/2vYG4HM0HzSjcbttsH1X60G9Ldx/NKuAWSPqPgC4p9z+LM0B9oNsz6A5PjHaYzleq2m6MobtP5GFSPojmq6YP6bZe92N5gO13eP1W9tn2z6YZs/jDTR7O3fTvBZmtTzXM2y3PeaxtUiAP2UpcIqk7SUN0vQFTkpZ1sE0fYzPAj7RZh5J2lfSWcAZNG8QJL1U0sskbU/z4fIbmt1sgDU0Zy8M25nmDT5U7nsa5eDsBO0JvLvU/0bgYJoQnIgzgVMlfUDS7qW+wyR9qUxfA+wu6Xda7rMGmL2lA0i2h4BrgS8A/2F7WZm0A01LagjYKOlYmuMJo1kKvEXSdqVPtrV74J+BPyvPgyTtLOm4EWE3XM8vy7LOkrSjmoPIh9J8mLTzU+AMSc+U9ExgHk2f+XCr+khJO5RlfYCmNfmDLWzHhNi+G/gh8LdlXYcCp9McZ4FmD+EhYIOkF9CcQdRq5GtxPC4FTpN0cDle8lcTXM6uwEbgPmB7moP0O7ebUdLRak4GeBrNdj0GPF4eh+8B/yBphqSnSXqupFe2W87WIgH+lP9Nc/BiHU1f3EVbnn2L3lR2Z9cDi2n6OF9iu7UVu0+ZZwPNm/n3gKNsD5/vO4MmQNbR7NLeT9OqBDgfeGHZ1fua7VuA/0PT2l1TljWZN/t1wEE0b4iPAifZvn8iC7L9Q5o+6qOB5WrOgllI+UCwfSvNB9zysj370LSuAe5v7eds4yKaA2BPPlelK+DdNOGwjqZ7ZfEWlvEemr2j9TQtsa+1LGsJTT/4p8uy7qAcgBvFKTQHv9YBC2get+EP1bdKam2Nv52mj3slTWv3OS3L3pWm5buuTDsGOHaiz0EH3lxqWUVzNsxZtq8q095P8xg+TPN6HHmg8mxgUXnuTh7PSm1/G/gUTR//HTSvX2iOM4zHt2i6RW4HVtAE82jHXfahOVngIZq9o+/QvP4A/oQm+G+heewvo4t74r0g5wcdooWkU4EzbP9+v2uJ6aXsrd4EPKMcjIwxpAUeEX0j6Q2lq2g3mu9AfD3h3bkE+DQk6XPa9OvIw3+f63dtMe28g+Z4xZ00x3hG9rHHFqQLJSKiUmmBR0RUasouagSwxx57ePbs2VO5yoiI6l1//fX32d7swmhTGuCzZ89myZIlU7nKiIjqSfpVu/HpQomIqFQCPCKiUgnwiIhKJcAjIiqVAI+IqFQCPCKiUgnwiIhKJcAjIiqVAI+IqNSUfhMztl2z53+z7fgVCybyW8gR0Ym0wCMiKpUAj4ioVAI8IqJSCfCIiEolwCMiKpUAj4ioVAI8IqJSCfCIiEolwCMiKjVmgEt6vqSlLX8PSXqvpFmSrpJ0e/m/21QUHBERjTED3PZttg+3fTjwEuAR4KvAfOBq2wcBV5fhiIiYIuPtQpkD3Gn7V8AJwKIyfhFwYjcLi4iILRtvgJ8CXFxu72V7NUD5v2c3C4uIiC3rOMAl7QC8HrhsPCuQNE/SEklLhoaGxltfRESMYjwt8GOBG2yvKcNrJO0NUP6vbXcn2wttD9oeHBgYmFy1ERHxpPEE+Jt5qvsEYDEwt9yeC1zRraIiImJsHQW4pJ2AVwNfaRm9AHi1pNvLtAXdLy8iIkbT0S/y2H4E2H3EuPtpzkqJiIg+yDcxIyIqlQCPiKhUAjwiolIJ8IiISiXAIyIqlQCPiKhUAjwiolIJ8IiISiXAIyIqlQCPiKhUAjwiolIJ8IiISiXAIyIqlQCPiKhUAjwiolIJ8IiISiXAIyIqlQCPiKhUAjwiolId/SampJnAecAhgIG3A7cBlwCzgRXAybbX9aTKmDZmz/9m2/ErFhw3xZVEbP06bYF/EvgX2y8ADgOWAfOBq20fBFxdhiMiYoqMGeCSZgCvBM4HsP1b2+uBE4BFZbZFwIm9KjIiIjbXSQv8OcAQ8AVJP5N0nqSdgb1srwYo//dsd2dJ8yQtkbRkaGioa4VHREx3nQT404EXA5+1/SLg14yju8T2QtuDtgcHBgYmWGZERIzUSYCvBFbavq4MX04T6Gsk7Q1Q/q/tTYkREdHOmAFu+17gbknPL6PmALcAi4G5Zdxc4IqeVBgREW11dBoh8D+BCyXtACwHTqMJ/0slnQ7cBbyxNyVGREQ7HQW47aXAYJtJc7pbTkREdCrfxIyIqFQCPCKiUgnwiIhKJcAjIiqVAI+IqFSnpxFGTEiuLhjRO2mBR0RUKgEeEVGpBHhERKUS4BERlUqAR0RUKmehRF+MdnZKv9abs2KiRmmBR0RUKgEeEVGpBHhERKUS4BERlcpBzOhYvw48RkR7aYFHRFQqAR4RUamOulAkrQAeBh4HNtoelDQLuASYDawATra9rjdlRkTESONpgf+R7cNtD/+48XzgatsHAVeX4YiImCKT6UI5AVhUbi8CTpx8ORER0alOA9zAlZKulzSvjNvL9mqA8n/PdneUNE/SEklLhoaGJl9xREQAnZ9GeKTtVZL2BK6SdGunK7C9EFgIMDg46AnUGBERbXTUAre9qvxfC3wVOAJYI2lvgPJ/ba+KjIiIzY0Z4JJ2lrTr8G3gNcBNwGJgbpltLnBFr4qMiIjNddKFshfwVUnD819k+18k/RS4VNLpwF3AG3tXZkREjDRmgNteDhzWZvz9wJxeFBUREWPLNzEjIiqVAI+IqFQCPCKiUgnwiIhKJcAjIiqVAI+IqFQCPCKiUgnwiIhKJcAjIiqVAI+IqFQCPCKiUgnwiIhKJcAjIiqVAI+IqFQCPCKiUgnwiIhKJcAjIiqVAI+IqFTHAS5pO0k/k/SNMvxsSddJul3SJZJ26F2ZERExUic/ajzsPcAyYEYZ/jhwju0vSfoccDrw2S7XF30we/43+11CRHSgoxa4pP2A44DzyrCAo4HLyyyLgBN7UWBERLTXaRfKucCZwBNleHdgve2NZXglsG+7O0qaJ2mJpCVDQ0OTKjYiIp4yZoBLOh5Ya/v61tFtZnW7+9teaHvQ9uDAwMAEy4yIiJE66QM/Eni9pNcCO9L0gZ8LzJT09NIK3w9Y1bsyIyJipDFb4Lb/0vZ+tmcDpwDftf1W4BrgpDLbXOCKnlUZERGbmcx54B8E/kLSHTR94ud3p6SIiOjEeE4jxPa1wLXl9nLgiO6XFBERncg3MSMiKpUAj4ioVAI8IqJSCfCIiEolwCMiKpUAj4ioVAI8IqJSCfCIiEqN64s8Ef0y2jXKVyw4booridh6pAUeEVGpBHhERKUS4BERlUqAR0RUKgEeEVGpBHhERKUS4BERlUqAR0RUKgEeEVGpBHhERKXGDHBJO0r6iaQbJd0s6a/L+GdLuk7S7ZIukbRD78uNiIhhnbTA/xM42vZhwOHAMZJeDnwcOMf2QcA64PTelRkRESONGeBubCiD25c/A0cDl5fxi4ATe1JhRES01VEfuKTtJC0F1gJXAXcC621vLLOsBPYd5b7zJC2RtGRoaKgbNUdEBB0GuO3HbR8O7AccARzcbrZR7rvQ9qDtwYGBgYlXGhERmxjXWSi21wPXAi8HZkoavp74fsCq7pYWERFbMuYPOkgaAB6zvV7SM4FX0RzAvAY4CfgSMBe4opeFRveN9iMJEVGHTn6RZ29gkaTtaFrsl9r+hqRbgC9J+gjwM+D8HtYZEREjjBngtn8OvKjN+OU0/eEREdEH+SZmRESlEuAREZVKgEdEVCoBHhFRqQR4RESlOjmNMCK6YLTz7lcsOG6KK4ltRVrgERGVSoBHRFQqXShRta2tWyKXJ4iplBZ4RESlEuAREZVKgEdEVCoBHhFRqRzEjCAHH6NOaYFHRFQqAR4RUakEeEREpRLgERGVGjPAJe0v6RpJyyTdLOk9ZfwsSVdJur3836335UZExLBOzkLZCLzP9g2SdgWul3QVcCpwte0FkuYD84EP9q7UiG3T1nY5gKjHmC1w26tt31BuPwwsA/YFTgAWldkWASf2qsiIiNjcuPrAJc2m+YX664C9bK+GJuSBPbtdXEREjK7jAJe0C/Bl4L22HxrH/eZJWiJpydDQ0ERqjIiINjoKcEnb04T3hba/UkavkbR3mb43sLbdfW0vtD1oe3BgYKAbNUdEBJ2dhSLgfGCZ7U+0TFoMzC235wJXdL+8iIgYTSdnoRwJvA34haSlZdyHgAXApZJOB+4C3tibEiMiop0xA9z2vwMaZfKc7pYTERGdytUII7ZSOT88xpKv0kdEVCoBHhFRqXShxDYpP9AQ00Fa4BERlUqAR0RUKgEeEVGpBHhERKUS4BERlUqAR0RUKgEeEVGpBHhERKUS4BERlUqAR0RUKgEeEVGpBHhERKUS4BERlUqAR0RUKgEeEVGpMa8HLunzwPHAWtuHlHGzgEuA2cAK4GTb63pXZkQMy0+txbBOWuAXAMeMGDcfuNr2QcDVZTgiIqbQmAFu+9+AB0aMPgFYVG4vAk7scl0RETGGif6k2l62VwPYXi1pz9FmlDQPmAdwwAEHTHB1ETFR6XLZdvX8IKbthbYHbQ8ODAz0enUREdPGRAN8jaS9Acr/td0rKSIiOjHRLpTFwFxgQfl/RdcqignLrnLE9DJmC1zSxcCPgOdLWinpdJrgfrWk24FXl+GIiJhCY7bAbb95lElzulxLRESMQ76JGRFRqQR4RESlJnoQMyoy2sHNmN5y0Lt+aYFHRFQqAR4RUal0oWzFsosbEVuSFnhERKUS4BERlUoXyhTq1tkgOaskIiAt8IiIaiXAIyIqlS6UiG1Ev7roclZU/6QFHhFRqQR4RESlpl0XSje/HJMv2kTkfdBPaYFHRFSqmhZ4vz7lJ3JgKOdpR8RUSAs8IqJSCfCIiEpNqgtF0jHAJ4HtgPNsbzU/bjzebox0e0RMnW51ifbrfbu1HKCdcAtc0nbAZ4BjgRcCb5b0wm4VFhERWzaZLpQjgDtsL7f9W+BLwAndKSsiIsYi2xO7o3QScIztM8rw24CX2X7XiPnmAfPK4POB2yZebl/sAdzX7yKmWLZ5esg21+NA2wMjR06mD1xtxm32aWB7IbBwEuvpK0lLbA/2u46plG2eHrLN9ZtMF8pKYP+W4f2AVZMrJyIiOjWZAP8pcJCkZ0vaATgFWNydsiIiYiwT7kKxvVHSu4B/pTmN8PO2b+5aZVuPart/JiHbPD1kmys34YOYERHRX/kmZkREpRLgERGVSoCPg6T3S7KkPfpdS69J+ntJt0r6uaSvSprZ75p6RdIxkm6TdIek+f2up9ck7S/pGknLJN0s6T39rmkqSNpO0s8kfaPftXRLArxDkvYHXg3c1e9apshVwCG2DwV+Cfxln+vpiWl6SYiNwPtsHwy8HPgf02CbAd4DLOt3Ed2UAO/cOcCZtPmy0rbI9pW2N5bBH9Oc578tmnaXhLC92vYN5fbDNKG2b3+r6i1J+wHHAef1u5ZuSoB3QNLrgXts39jvWvrk7cC3+11Ej+wL3N0yvJJtPMxaSZoNvAi4rr+V9Ny5NA2wJ/pdSDdV84s8vSbpO8Cz2kz6MPAh4DVTW1HvbWmbbV9R5vkwzS73hVNZ2xTq6JIQ2yJJuwBfBt5r+6F+19Mrko4H1tq+XtJR/a6nmxLghe1XtRsv6feAZwM3SoKmK+EGSUfYvncKS+y60bZ5mKS5wPHAHG+7XxiYlpeEkLQ9TXhfaPsr/a6nx44EXi/ptcCOwAxJX7T9J32ua9LyRZ5xkrQCGLRd4xXNOlZ+rOMTwB/aHup3Pb0i6ek0B2nnAPfQXCLiLdvot4oBUNMSWQQ8YPu9/a5nKpUW+PttH9/vWrohfeAxmk8DuwJXSVoq6XP9LqgXyoHa4UtCLAMu3ZbDuzgSeBtwdHlul5bWaVQmLfCIiEqlBR4RUakEeEREpRLgERGVSoBHRFQqAR4RUakEeEwLkh4vp8vdJOkySTuNMf8Fkk4qt6+VtM38EG5sOxLgMV08avtw24cAvwX+rN8FRUxWAjymo+8Dz5U0W9JNwyPL9d7P7l9ZEeOTAI9ppXx1/ljgF/2uJWKyEuAxXTxT0lJgCc2Pcpzf53oiJi1XI4zp4lHbh7eOkLSRTRsxO05tSRGTkxZ4TGdrgD0l7S7pGTSXzo2oRlrgMW3ZfkzS39D8Gs1/ALf2uaSIccnVCCMiKpUulIiISiXAIyIqlQCPiKhUAjwiolIJ8IiISiXAIyIqlQCPiKjU/wcpA5BieJoBAwAAAABJRU5ErkJggg==\n", "text/plain": [ "
" ] @@ -2403,7 +2403,7 @@ " plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty))\n", " plt.hist(pull_dic[key][step], bins = 50, range = (-5,5))\n", " plt.xlabel('Pull')\n", - " plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty))\n" + " plt.savefig('data/CLs/plots/{}/{:.2f}Ctt{}s{}f.png'.format(key, Ctt_steps[int(step/2)], step, floaty))" ] }, { @@ -2418,61 +2418,61 @@ "output_type": "stream", "text": [ "BR: 0.0003\n", - "0.893048128342246\n", + "0.7243460764587525\n", "\n", "BR: 0.0004\n", - "0.7967914438502673\n", + "0.6056338028169014\n", "\n", "BR: 0.0006\n", - "0.6737967914438503\n", + "0.5533199195171026\n", "\n", "BR: 0.0007\n", - "0.6363636363636364\n", + "0.44466800804828976\n", "\n", "BR: 0.0009\n", - "0.44919786096256686\n", + "0.3501006036217304\n", "\n", "BR: 0.0010\n", - "0.43315508021390375\n", + "0.29577464788732394\n", "\n", "BR: 0.0012\n", - "0.32085561497326204\n", + "0.23541247484909456\n", "\n", "BR: 0.0013\n", - "0.2727272727272727\n", + "0.20724346076458752\n", "\n", "BR: 0.0015\n", - "0.19786096256684493\n", + "0.1750503018108652\n", "\n", "BR: 0.0016\n", - "0.1925133689839572\n", + "0.13883299798792756\n", "\n", "BR: 0.0018\n", - "0.1443850267379679\n", + "0.08853118712273642\n", "\n", "BR: 0.0019\n", - "0.1497326203208556\n", + "0.096579476861167\n", "\n", "BR: 0.0021\n", - "0.10695187165775401\n", + "0.1006036217303823\n", "\n", "BR: 0.0022\n", - "0.058823529411764705\n", + "0.060362173038229376\n", "\n", "BR: 0.0024\n", - "0.058823529411764705\n", + "0.04024144869215292\n", "\n", "BR: 0.0025\n", - "0.058823529411764705\n", + "0.04225352112676056\n", "\n", "BR: 0.0027\n", - "0.0427807486631016\n", + "0.026156941649899398\n", "\n", "BR: 0.0028\n", - "0.0481283422459893\n", + "0.030181086519114688\n", "\n", "BR: 0.0030\n", - "0.0374331550802139\n", + "0.028169014084507043\n", "\n" ] } @@ -2480,8 +2480,17 @@ "source": [ "for s in range(len(l)):\n", " print('BR: {:.4f}'.format(BR_steps[s+1]))\n", - " print(2*l[s]/len(CLs_values[s]))\n", - " print()" + " print(l[s]/len(np.where(np.array(CLs_values[0]) < np.mean(CLs_values[0]))[0]))\n", + " print()\n", + "# print(l[s], len(CLs_values[s]))\n", + "# print()\n", + "# print(len(CLs_values[0])/2)\n", + "# print(len(np.where(np.array(CLs_values[0]) < np.mean(CLs_values[0]))[0]))\n", + "# plt.clf()\n", + "# # plt.title('Pull {} - Ctt value {:.2f} - floating {}'.format(key, Ctt_steps[int(step/2)], floaty))\n", + "# plt.hist(CLs_values[0], bins = 150, range = (-25, 50), label = 'Ctt fixed to 0')\n", + "# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted')\n", + "# plt.show()" ] }, { @@ -2515,7 +2524,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "2 min, 51 s\n" + "3 min, 1 \n" ] } ],